Php 如果字符串包含特定值,则从preg_match_all中排除字符串

Php 如果字符串包含特定值,则从preg_match_all中排除字符串,php,magento2,preg-match-all,Php,Magento2,Preg Match All,我使用preg_match_all抓取所有脚本,并将其放置在正文末尾,如下所示: preg_match_all('#(<script.*?</script>)#is', $html, $matches); $js = ''; foreach ($matches[0] as $value): $js .= $value; endforeach; $html = preg_replace('#(<script.*?</script>)#is', '', $

我使用preg_match_all抓取所有脚本,并将其放置在正文末尾,如下所示:

preg_match_all('#(<script.*?</script>)#is', $html, $matches);
$js = '';
foreach ($matches[0] as $value):
    $js .= $value;
endforeach;
$html = preg_replace('#(<script.*?</script>)#is', '', $html);
$html = preg_replace('#</body>#',$js.'</body>',$html);
<script data-template="bundle-summary" type="text/x-magento-template">
      <li>
            <strong class="label"><%- data._label_ %>:</strong>
            <div data-container="options"></div>
      </li>
</script>
if (strpos($value, 'type="text/x-magento-template"') === false) {
    $js .= $value;
}
然后它将不会被添加到$js变量中,但是我不确定如何停止删除以下行中的相同脚本:

$html = preg_replace('#(<script.*?</script>)#is', '', $html);

计时后,使用if语句的方法与未使用if语句的方法之间的差异可以忽略不计,每次的时间约为0.005秒,因此我很高兴离开它。

对于html编辑,DOM方法可以提供更好的结果:

$dom = new DOMDocument;
$state = libxml_use_internal_errors(true);
$dom->loadHTML($html); // or $dom->loadHTMLFile('./file.html'); 

$removeList=[];
$bodyNode = $dom->getElementsByTagName('body')->item(0);

foreach ($dom->getElementsByTagName('script') as $scriptNode) {
    if ( $scriptNode->hasAttribute('type') && $scriptNode->getAttribute('type')=='text/x-magento-template' )
        continue;

    $removeList[] = $scriptNode;
}

foreach ($removeList as $scriptNode) {
    $bodyNode->appendChild($scriptNode);
}

libxml_use_internal_errors($state);

echo $dom->saveHTML();

使用这段代码,您不必删除脚本节点,因为它们从dom树中的当前位置移动到正文元素的末尾,因为它们被追加了。

谢谢这看起来很好,我会尝试一下。@harri:不用使用片段就可以做到,我会编辑我的文章。看起来很好,但似乎需要10倍的时间。0.005对0。05@harri:将这种脚本与不起作用的脚本进行比较是毫无意义的。如果您计划在每次调用页面时运行此脚本,那么您的应用程序中就有一个很大的设计问题。你要做的事必须一劳永逸。谢谢你的帮助,我以后可能会参考这一点,并标记为答案。
$dom = new DOMDocument;
$state = libxml_use_internal_errors(true);
$dom->loadHTML($html); // or $dom->loadHTMLFile('./file.html'); 

$removeList=[];
$bodyNode = $dom->getElementsByTagName('body')->item(0);

foreach ($dom->getElementsByTagName('script') as $scriptNode) {
    if ( $scriptNode->hasAttribute('type') && $scriptNode->getAttribute('type')=='text/x-magento-template' )
        continue;

    $removeList[] = $scriptNode;
}

foreach ($removeList as $scriptNode) {
    $bodyNode->appendChild($scriptNode);
}

libxml_use_internal_errors($state);

echo $dom->saveHTML();