0

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

1 回答 1

0

您应该加载 HTMLDOMDocument并使用其操作来移动节点:

$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();
于 2013-05-23T03:14:45.297 回答