0

Using PHP.

I have an html document on a variable, I want to look inside this code for all instances of the img tag, and prepend some text to its src attribute, I want to avoid using client side code like javascript and let php handle all the heavy lifting, I was thinking of using regular expressions to do this, like find all instances of <img [ ]* src=" , Im not very savy on regex as you can see, how can I achieve this?

Thanks!

Barmar
  • 741,623
  • 53
  • 500
  • 612

2 Answers2

0

This will match all img tags and capture the contents inside src which then you can use to replace with something prepended to it.

/\<img.+src="(.+)".*\/\>/

You can see how it's working here: http://www.phpliveregex.com/p/3Mk

Stepan Grigoryan
  • 3,062
  • 1
  • 17
  • 6
0

Use a DOM parser, they're simple and so much less error prone.

That said, it's Friday, and if this was a one off fix to correct some broken URLs (say the image directory got moved up a level) in a few HTML files, I'd be whipping out Notepad++ and doing a quick regex find and replace.

/(<img[^>]*src=")/i

Replacing with \1whatever:

preg_replace('/(<[^>]*src=")/i', '\1whatever', $subject); 
OGHaza
  • 4,795
  • 7
  • 23
  • 29