繁体   English   中英

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

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

我已经为此苦苦挣扎了2个小时,这真让我发疯。 而且我认为这可能很难。 我正在使用Wordpress,需要将IMG网址从旧路径替换为新路径。 问题是..除了特定的随机目录之外,所有关于URL的信息都是静态的。

例:

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

应该成为

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

粗体部分是随机的。 所以我在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');

但这不起作用。 我不知道。 有什么帮助吗?

我认为您需要的是:

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');

尝试匹配URL时,使用不同于/分隔符会更好。

是运行中的脚本。

我使用以下代码确定了问题的答案

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