需要查找包含条件的单个<script> condition </script>。下面的示例包含4个标签,我需要匹配包含条件的第二个标签,并丢弃其他标签。从<script>开始。之前的条件可以是空格或换行符,然后像if (window.location.href == bar) { }和than这样的条件可以是空格或换行符,以及结束</script>。
<script> <!-- discard --->
other stuff
not to be found
</script>
<script> <!-- MATCH --->
if (window.location.href == bar) {
do something
}
</script>
<script> <!-- discard --->
other stuff
not to be found
</script>
<script> <!-- discard --->
other stuff
not to be found
</script>提前感谢
发布于 2017-04-30 10:58:31
在这里,您应该使用DOMDocument而不是Regex来匹配标记及其所需内容。
<?php
ini_set('display_errors', 1);
$object= new DOMDocument();
$object->loadHTML('<html><body><script> <!-- discard --->
other stuff
not to be found
</script>
<script> <!-- MATCH --->
if (window.location.href == bar) {
do something
}
</script>
<script> <!-- discard --->
other stuff
not to be found
</script>
<script> <!-- discard --->
other stuff
not to be found
</script></body></html>');
$tagsToRemove=array();
foreach($object->getElementsByTagName("script") as $element)
{
if($element instanceof DOMElement)
{
if(!preg_match("/if\s*\(/i", $element->nodeValue))
{
$tagsToRemove[]=$element;
}
}
}
foreach($tagsToRemove as $element)
{
$element->parentNode->removeChild($element);
}
echo $object->saveHTML();https://stackoverflow.com/questions/43702468
复制相似问题