I have been struggling with this now for 2 hours and it's driving me nuts. 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. Problem is..everything about the url is static except a particular directory which is random.
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
The bold part is random. So I have this in my 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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.