我想使用preg_replace将图像移动到大型文本中的容器段落上方。
所以,我可能有
$body = '<p><img src="a" alt="image"></p><img src="b" alt="image"><p>something here<img src="c" alt="image"> text</p>'
我想要什么(除了40英尺的游艇等等);
<img src="a" alt="image"><p></p><img src="b" alt="image"><img src="c" alt="image"><p>something here text</p>
我有这个,它不工作,
$body = preg_replace('/(<p>.*'s*)(<img.*'s*?image">)(.*'s*?<'/p>)/', '$2$1$3',$body);
结果是;
<img src="c" alt="image"><p><img src="a" alt="image"></p><img src="b" alt="image"><p>something here text</p>
您应该使用DOMDocument
加载HTML并使用其操作来移动节点:
$content = <<<EOM
<p><img src="a" alt="image"></p>
<img src="b" alt="image"><p>something here<img src="c" alt="image"> text</p>
EOM;
$doc = new DOMDocument;
$doc->loadHTML($content);
$xp = new DOMXPath($doc);
// find images that are a direct descendant of a paragraph
foreach ($xp->query('//p/img') as $img) {
$parent = $img->parentNode;
// move image as a previous sibling of its parent
$parent->parentNode->insertBefore($img, $parent);
}
echo $doc->saveHTML();