Add parent for each img using PHP

I would like to add a parent for each img with PHP. I can do this with wrap() in jQuery, but I do not do it with PHP.

HTML:

 <div id="main"> <img src="..." /> <img src="..." /> <img src="..." /> <img src="..." /> </div> 

JS:

 $("#main img").each(function(){ $(this).wrap('<div class="photo" />'); }); 

HTML RESULT:

 <div id="main"> <div class="photo"><img src="..." /></div> <div class="photo"><img src="..." /></div> <div class="photo"><img src="..." /></div> <div class="photo"><img src="..." /></div> </div> 
+4
source share
2 answers

You can do this with the function I did below.

 <?php $page = ' <body> <div id="main"> <img src="..." /> <img src="..." /> <img src="..." /> <img src="..." /> </div> </body> '; echo $page = wrapImg ( $page, 0 ); function wrapImg ( $page, $offset ) { if ( FALSE !== ( $startImg = strpos( $page, '<img', $offset ) ) && FALSE !== ( $endImg = strpos( $page, '/>', $startImg ) ) ) { $before = '<div class="photo">'; $after = '</div>'; $start = substr( $page, 0, $startImg ); $img = substr( $page, $startImg, $endImg+2-$startImg ); $end = substr( $page, $endImg+2); $page = $start . $before . $img . $after . $end; $length = ($startImg + strlen( $before . $img . $after )-1); $page = wrapImg ( $page, $length ); } return $page; } ?> 

The result will be:

  <body> <div id="main"> <div class="photo"><img src="..." /></div> <div class="photo"><img src="..." /></div> <div class="photo"><img src="..." /></div> <div class="photo"><img src="..." /></div> </div> </body> 
+1
source

A simple HTML DOM might be your answer.

+3
source

All Articles