仅当不包含给定部分时才替换 URL 的一部分

Replace part of URL only if doesn't contain a given part

我需要将所有包含 31.media.tumblr.com 的 URL 替换为 41.media.tumblr.com。但是如果URL31.media.tumblr.com里面有.gif,就一定不能改。

这是我的代码;但它改变了所有内容,甚至 URLs 中有 .gif... 当我 运行 它时:

UPDATE wp_posts 
    SET post_content 
      = REPLACE(post_content
               ,'31.media.tumblr.com/'
               ,'41.media.tumblr.com/') 
    WHERE post_content LIKE '%31.media.tumblr.com/%' 
      AND post_content NOT LIKE '%.gif';

p.s。这是 31 的示例。url 末尾有 gif

https://31.media.tumblr.com/79db8c1df4f893bc20d53063e03834f6/tumblr_n1e93kMh3z1rjbi2lo1_500.gif

您的查询看起来不错,我认为问题出在 post_content 中的尾随空格。尝试:

UPDATE wp_posts 
    SET post_content 
      = REPLACE(post_content
               ,'31.media.tumblr.com/'
               ,'41.media.tumblr.com/') 
WHERE post_content LIKE '%31.media.tumblr.com/%' 
  AND rtrim(post_content) NOT LIKE '%.gif';

看看是否有帮助。测试用例:

create table wp_posts (post_content varchar(255));
insert into wp_posts 
values ('https://31.media.tumblr.com/79db8c1df4f893bc20d53063e03834f6/tumblr_n1e93kMh3z1rjbi2lo1_500.gif')
insert into wp_posts 
values ('https://31.media.tumblr.com/79db8c1df4f893bc20d53063e03834f6/tumblr_n1e93kMh3z1rjbi2lo1_500.gif ');

select * from wp_posts 
where post_content LIKE '%31.media.tumblr.com/%' 
  AND post_content NOT LIKE '%.gif';
[...]
1 row in set (0.00 sec)

select * from wp_posts 
where post_content LIKE '%31.media.tumblr.com/%' 
  AND rtrim(post_content) NOT LIKE '%.gif';
[...]
Empty set (0.00 sec)

你提供的那个例子 URL 是一张图片,所以我想它在 <img> 标签之类的东西里面,如果是的话......你需要做的就是添加 % 通配符在 .gif 的末尾。这可能就是脚本无法正常工作的原因。

试试这个

UPDATE wp_posts SET post_content = REPLACE(post_content,'31.media.tumblr.com/','41.media.tumblr.com/')
WHERE post_content LIKE '%31.media.tumblr.com/%' 
AND post_content NOT LIKE '%.gif%';