简体   繁体   English

使用preg_replace需要替换图像src中的随机目录

[英]Using preg_replace need to replace random directory in an image src

I have been struggling with this now for 2 hours and it's driving me nuts. 我已经为此苦苦挣扎了2个小时,这真让我发疯。 And I don't think it is likely hard. 而且我认为这可能很难。 I am using Wordpress and need to replace the IMG urls from an old path to a new path. 我正在使用Wordpress,需要将IMG网址从旧路径替换为新路径。 Problem is..everything about the url is static except a particular directory which is random. 问题是..除了特定的随机目录之外,所有关于URL的信息都是静态的。

Example: 例:

https://cdn2.content.mysite.com/uploads/user/76eb326b-62ff-4d37-bf4b-01a428e2f9f6/0ffd6c15-8a13-437c-9661-36edfe11cb41/Image/ b1493cd89a29c0a2d1d8e0939f05d8ee /booth_w640.jpeg

should become 应该成为

/wp-content/uploads/imports/booth_w640.jpeg /wp-content/uploads/imports/booth_w640.jpeg

The bold part is random. 粗体部分是随机的。 So I have this in my wordpress functions.php 所以我在wordpress functions.php中有这个

function replace_content($content) {
    $reg = '#/https://cdn2.content.mysite.com/uploads/user/76eb326b-62ff-4d37-bf4b-01a428e2f9f6/0ffd6c15-8a13-437c-9661-36edfe11cb41/Image/([^/]+)#i';
    $rep = '/wp-content/uploads/imports';
    $content = preg_replace($reg, $rep ,$content);
    return $content;
}
add_filter('the_content','replace_content');

but that isn't working. 但这不起作用。 I can't figure it out. 我不知道。 Any help? 有什么帮助吗?

I think what you need is: 我认为您需要的是:

function replace_content($content) {
    $reg = '#/static-part-of-url/([^/]+)#i';
    $rep = '/wp-content/uploads/imports';
    $content = preg_replace($reg, $rep ,$content);
    return $content;
}
add_filter('the_content','replace_content');

Using a different delimiter than / is better when trying to match URLs. 尝试匹配URL时,使用不同于/分隔符会更好。

Here is the script in action. 是运行中的脚本。

I determined the answer to my problem using the below code 我使用以下代码确定了问题的答案

preg_match( '/src="([^"]*)"/i', $content, $match ) ;
$getURL = $match[1];
$urlArr = explode("/",$getURL);
$fileName = end($urlArr);
$newURL = "/blog/wp-content/uploads/imports/" . $fileName;
$content = str_replace($getURL, $newURL, $content);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM