如果模式不在另一个模式之后,则正则表达式匹配 - PHP

Regex match if pattern is not after another patten - PHP

我想将 iframe 对象包装在 div class 中,但前提是它尚未包装在 div class 中。我正在尝试为 div class 使用否定匹配模式,因此 preg_replace 将不匹配并且 return 原始 $content。但是它仍然匹配:

<?php
$content = <<< EOL
<div class="aoa_wrap"><iframe width="500" height="281" src="https://www.youtube.com/embed/uuZE_IRwLNI" frameborder="0" allowfullscreen></iframe></div>
EOL;
$pattern = "~(?!<div(.*?)aoa_wrap(.*?)>)<iframe\b[^>]*>(?:(.*?)?</iframe>)?~";
$replace = '<div class="aoa_wrap">[=11=]</div>';
$content = preg_replace( $pattern, $replace, $content);
echo $content . "\n";
?>

输出(不正确):

<div class="aoa_wrap"><div class="aoa_wrap"><iframe width="500" height="281" src="https://www.youtube.com/embed/uuZE_IRwLNI" frameborder="0" allowfullscreen></iframe></div></div>

我不确定为什么开头的否定模式没有按预期导致 preg_replace 到 return 原始 $content。我是否漏掉了一些明显的东西?

我最终按照上述评论中的建议尝试 DOM。这对我有用:

<?php

$content = <<< EOL
<p>something here</p>
<iframe width="500" height="281" src="https://www.youtube.com/embed/uuZE_IRwLNI" frameborder="0" allowfullscreen></iframe>
<p><img src="test.jpg" /></p>
EOL;

$doc = new DOMDocument();
$doc->loadHTML( "<div>" . $content . "</div>" );


// remove <!DOCTYPE  and html and body tags that loadHTML adds:

$container = $doc->getElementsByTagName('div')->item(0);
$container = $container->parentNode->removeChild($container);
while ($doc->firstChild) {
    $doc->removeChild($doc->firstChild);
}
while ($container->firstChild ) {
    $doc->appendChild($container->firstChild);
}


// get all iframes and see if we need to wrap them in our aoa_wrap class:

$nodes = $doc->getElementsByTagName( 'iframe' );

foreach ( $nodes as $node ) {

        $parent = $node->parentNode;
        // skip if already wrapped in div class 'aoa_wrap'
        if ( isset( $parent->tagName ) && 'div' == $parent->tagName && 'aoa_wrap' == $parent->getAttribute( 'class' ) ) { 
                continue;
        }

        // create new element for class "aoa_wrap"
        $wrap = $doc->createElement( "div" );
        $wrap->setAttribute( "class", "aoa_wrap" );

        // clone the iframe node as child
        $wrap->appendChild( $node->cloneNode( true ) );

        // replace original iframe node with new div class wrapper node
        $parent->replaceChild( $wrap, $node );

}

echo $doc->saveHTML();

?>