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!
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
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);
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.