Regex to replace html src attribute in PHP
html, php, regex
Solution
You have to use the `e` modifier.
$string = "<html><body><img src='images/test.jpg' /><img src='http://test.com/images/test3.jpg'/><video controls=\"controls\" src='../videos/movie.ogg'></video></body></html>";
$string2 = preg_replace("~src=[']([^']+)[']~e", '"src=\'" . convert_url("$1") . "\'"', $string);
Note that when using the `e` modifier, the replacement script fragment needs to be a string to prevent it from being interpreted before the call to preg_replace.
Problem
I'm trying to use regex to replace source attribute (could be image or any tag) in PHP. I've a string like this: ``` $string2 = "<html><body><img src = 'images/test.jpg' /><img src = 'http://test.com/images/test3.jpg'/><video controls="controls" src='../videos/movie.ogg'></video></body></html>"; ``` And I would like to turn it into: ``` $string2 = "<html><body><img src = 'test.jpg' /><img src = 'test3.jpg'/><video controls="controls" src='movie.ogg'></video></body></html>"; ``` Heres what I tried : ``` $string2 = preg_replace("/src=["']([/])(.*)?["'] /", "'src=' . convert_url('$1') . ')'" , $string2); echo htmlentities ($string2); ``` Basically it didn't change anything and gave me a warning about unescaped string. Doesn't `$1` send the content of the string ? What is wrong here ? And the function of convert_url is from an example I posted here before : ``` function convert_url($url) { if (preg_match('#^https?://#', $url)) { $url = parse_url($url, PHP_URL_PATH); } return basename($url); } ``` It's supposed to strip out url paths and just return the filename.