Skip to content
Advertisement

Change the src part of an img tag

I’ve got a string containing html code, and I want to change <img src="anything.jpg"> to <img src="'.DOC_ROOT .'anything.jpg"> everytime it occurs in the string. I really don’t want to use an html parser, since this will be the only thing I’ll be using it for. Does anyone know how to do this in php, using a regex for example?

Advertisement

Answer

You really should use a parser but since you made clear that you really don’t want to do that, you can use the following regex replace:

$string = preg_replace('/<img([^>]*)src=["']([^"'\/][^"']*)["']/', '<img1src="'.DOC_ROOT.'2"', $string);

Demo. This regular expression will not modify any urls that are already a relative path. Change it to the following if you do want to match those:

$string = preg_replace('/<img([^>]*)src=["']["'\/]?([^"']*)["']/', '<img1src="'.DOC_ROOT.'2"', $string);

Demo.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement