Given the following code :
<body> <img src='source.jpg' /> <p> <img src='source.jpg' id ='hello' alt='nothing' /> <img src='source.jpg' id ='world'/> </p> </body>
What’s the best way – using a regular expression (or better?) – to replace it so it becomes this:
<body> <img src='source.jpg' id='img_0' /> <p> <img src='source.jpg' id ='img_1' alt='nothing' /> <img src='source.jpg' id ='img_2'/> </p> </body>
In other words :
-
All the
<image />tags all gets populated by anidattribute. -
The
idattribute should contain an incremented attribute (this is not really the problem though as its just part of the replace procedure)
I guess two passes are needed, one to remove all the existent id attributes and another to populate with new ones ?
I think the best approach is to use
preg_replace_callback.Also I would recommend a slightly more stringent
regexpthan those suggested so far – what if your page contains an<img />tag that does not contain anidattribute?Which produces the following for me:
The
regexphas two capturing groups, the first we preserve, the second we replace. I’ve used lots of negative character classes (e.g.[^>]*= up to closing>) to make sure that<img />tags arn’t required to haveidattributes.