I have in my string $content many url:
<a href="https://domain/wp-content/uploads/2018/07/sample-Wokal-2.jpg"><img class="alignright size-full wp-image-6608" src="https://domain/wp-content/uploads/2018/07/sample-Wokal-2.jpg" alt="sample Wokal 2" width="933" height="617" /></a>
<a href="https://domain/wp-content/uploads/2014/01/sample-lato-123.jpg"><img class="alignright size-full wp-image-6608" src="https://domain/uploads/2014/01/sample-lato-123.jpg" alt="sample lato 123" width="933" height="617" /></a>
etc
Is it possible replace all links to: - https://domain/files/sample-lato-123.jpg , - https://domain/files/sample-Wokal-2.jpg ,
etc?
How to do it? I tried str_replace - but I have different types of links and I do not know how to replace them. I do not know about regular expressions :(
Please help.
You can use this regex which does lookarounds to ensure the string that needs to be replaced is indeed the one we want,
(?<=domain).*?(?=sample)
and replace with
/files/
Here is sample PHP code,
$str = '<a href="https://domain/wp-content/uploads/2018/07/sample-Wokal-2.jpg"><img class="alignright size-full wp-image-6608" src="https://domain/wp-content/uploads/2018/07/sample-Wokal-2.jpg" alt="sample Wokal 2" width="933" height="617" /></a>\n<a href="https://domain/wp-content/uploads/2014/01/sample-lato-123.jpg"><img class="alignright size-full wp-image-6608" src="https://domain/uploads/2014/01/sample-lato-123.jpg" alt="sample lato 123" width="933" height="617" /></a>';
echo preg_replace('/(?<=domain).*?(?=sample)/', '/files/', $str);
Prints,
<a href="https://domain/files/sample-Wokal-2.jpg"><img class="alignright size-full wp-image-6608" src="https://domain/files/sample-Wokal-2.jpg" alt="sample Wokal 2" width="933" height="617" /></a>\n<a href="https://domain/files/sample-lato-123.jpg"><img class="alignright size-full wp-image-6608" src="https://domain/files/sample-lato-123.jpg" alt="sample lato 123" width="933" height="617" /></a>
Let me know if this works fine for you.
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.