php - how to enumerate items with preg_replace? -


i need add tags before , after images on document , numerate them @ once. html document code is:

....

<img src="http://img.example.com/img/mage1.jpg" alt="sometile"> <br>  <img src="http://img.example.com/img/image72.jpg" alt="sometile"> <br>  <img src="http://img.example.com/img/imagstr.jpg" alt="sometile"> <br>  <img src="http://img.example.com/img/image.jpg" alt="sometile"> <br>  <img src="http://img.example.com/img/imgger.gif" alt="sometile"> <br>  <img src="http://img.example.com/img/somepic.png" alt="sometile"> <br>  

i need in result code

<div><a name="#pic1"></a><img src="http://img.example.com/img/mage1.jpg" alt="sometile"></div> <div><a name="#pic2"></a><img src="http://img.example.com/img/image72.jpg" alt="sometile"> </div>  <div><a name="#pic3"></a><img src="http://img.example.com/img/imagstr.jpg" alt="sometile"> </div>  <div><a name="#pic4"></a><img src="http://img.example.com/img/image.jpg" alt="sometile"> </div>  <div><a name="#pic5"></a><img src="http://img.example.com/img/imgger.gif" alt="sometile"> </div>  <div><a name="#pic6"></a><img src="http://img.example.com/img/somepic.png" alt="sometile"> </div>  

i'm not fan of regex+html, here goes (i cooked simple regex—you have one):

$s = '<img src="http://img.example.com/img/mage1.jpg" alt="sometile"> <br>  <img src="http://img.example.com/img/image72.jpg" alt="sometile"> <br>  <img src="http://img.example.com/img/imagstr.jpg" alt="sometile"> <br>  <img src="http://img.example.com/img/image.jpg" alt="sometile"> <br>  <img src="http://img.example.com/img/imgger.gif" alt="sometile"> <br>  <img src="http://img.example.com/img/somepic.png" alt="sometile"> <br>';  $i = 0; function wrap($s) {         global $i;         $i++;         return sprintf('<div><a name="pic%d">%s</div>', $i, $s); }  print preg_replace('#(<img [^>]+?>) <br>#e', "wrap('\\1')", $s); 

(demo)

the important part e modifier in preg_replace(). see "example #4 using 'e' modifier."


edit
pointed out in comments, $i not best name global variable. if going used simple "one-off" transformation may alright. if not, change name not conflict. or put public static in class.

also, preg_replace_callback() exists. it's better suited, although find passing function name string , evaluating functionname('arg') equally ugly :)


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -