In PHP how to search div and add wrapper container divs
In PHP I want to search div and the images coming inside div need to add wrapping divs, like
<开发者_高级运维;div id="div1"><img src="test1.jpg" /></div><div id="div2"><img src="test1.jpg" /><img src="test2.jpg" /></div>
Whatever images are coming inside <div id="div2">
I need to reformat, like
<div id="div2"><div id="imageContainer"><img src="test1.jpg" /></div><div id="imageContainer"><img src="test2.jpg" /></div></div>
Thanks, coder
best practice is to use an XML Parser, like
DOM
like this you can get a value:
function getXpathValues(&$dom, $expr) {
$xpth = $dom->xpath_new_context();
$xnode = xpath_eval($xpth,$expr);
if (isset ($xnode->nodeset[0])) {
$firstnode = $xnode->nodeset[0];
$children = $firstnode->children();
$value = $children[0]->content;
return $value;
}
else return Null;
}
Usage :
$dom = domxml_open_file('pear.rss');
echo $this->getXpathValues($dom, "//channel/title");
taken form here: php manual
to really insert new elements go for this: xsl: for more complexity or loop the elements, add the child to a new one (div imageContainer), remove the childs, and add the new element
or really the simplest - just do a string replace ..
The easiest ways is to use preg_replace();
You search for the img tag and then you place a div around it
<?php preg_replace("/\[(img .*?)\]/","<div class='div2'><$1></div>", $content); ?>
But you say you are creating a wordpress template.. is the code, you posted above, submitted through a form or in the theme files?
精彩评论