preg_match移动选择上面的段落

时间:2013-05-22 07:39:35

标签: php preg-match

我想使用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>

1 个答案:

答案 0 :(得分:0)

您应该使用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();