Search code examples
phpimagereplacehtml-parsingsrc

Replace the src attribute value of all <img> tags in an HTML document


I have following code (php), it will match img-src and replace with new url

$rep = array('/', '+', '(', ')');
$with = array('\/', '\+', '\(', '\)');

$match_pattern = '/<img[^<]*src\s*=\s*\"'.str_replace($rep, $with, $source_url).'\"[^>]*>/iUu';
$img_replace_str = '<img src="'.$new_url.'" />';
$post_content = preg_replace($match_pattern, $img_replace_str, $post_content);

For images that have src as http://www.example.com/a.jpg, there is no issue, but for images that have src that contains query string like http://www.example.com/b.jpg?height=900, it's not matching.

I want to match image tags with and without a query string.


Solution

  • You can use PHP's preg_quote()-function instead of str_replace(). It automatically escapes all regular expression special characters (see the docs). That should solve the problem, since your str_replace()-solution did not escape ?, which is a special character in regular expressions:

    $match_pattern = '/<img[^<]*src\s*=\s*\"'.preg_quote($source_url, '/').'\"[^>]*>/iUu';