PHP 正则表达式匹配标记前瞻问题

标签 php regex google-analytics

我正在尝试检查网页是否存在 google 分析脚本标记。这看起来应该很容易,但我的正则表达式技能似乎缺乏。因此,作为一个简单的示例,我试图匹配它们之间具有“google-analytics”的打开和关闭脚本标签。

例如,如果您有:

<script scr="whatever"></script>
<script>other script</script>
blah blah blah
<script>
   blah blah google-analytics
<script>

然后是正则表达式:
/<script>([s/S/]*?google-analtics[s/S/]*?)<\/script>/

这将返回一个从第一个脚本标签开始的字符串,并包含其他脚本标签。所以像:
other script</script> blah blah blah <script> blah blah google-analytics

但当然我只想要字符串
blah blah google-analytics

所以下一步是包括一个负面的展望,比如:
 /<script>((?![s/S/]*?script)[s/S/]*?google-analytics[s/S/]*?)<\/script>/

但这似乎不起作用。我尝试了一堆不同的捕获组组合和 '[s/S/]*?'在前面和后面。

基本上我试图匹配一个字符串,只要它不包含子字符串。这听起来像是一个普遍的问题,但对于我来说,我无法去工作。我有很多谷歌,所有的例子都很简单,但似乎不起作用。我一直在使用 https://regex101.com/r/hN5dK5/2 进行测试

任何见解都会有所帮助。 (脚本作为 php 运行)

最佳答案

正则表达式方法

首先,使用 verbose模式具有更好的可读性。
然后考虑以下正则表达式:

<script>                 # match "<script>" literally
(?:(?!</script>)[\s\S])* # match anything except "</script>"
(?:google-analytics)     # look for "google-analytics" literally
(?:(?!</script>)[\s\S])* # same pattern as above
</script>                # closing "</script>" tag

your updated demo 中查看此方法的演示.

解析器方法

简单XML

一般分析HTMLSO 上使用正则表达式被认为是不好的做法(参见 this famous post ),因此您不妨使用带有解析器和适当的 xpath 的方法查询:
$xml = simplexml_load_string($html);
$scripts = $xml->xpath("//script[contains(text(),'google-analytics')]");
print_r($scripts);

demo on ideone.com .

DOM文档

有人可能会说,SimpleXML并非真正设计用于解析 HTML文件(而不是 XML 文件,顾名思义),所以为了完整起见,以 DOMDocument 为例终于:
$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DOMXpath($doc);
$scripts = $xpath->query("//script[contains(text(),'google-analytics')]");
foreach ($scripts as $script) {
    // do sth. useful here
    print_r($script);
}

关于PHP 正则表达式匹配标记前瞻问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36776208/

相关文章:

javascript - Google Analytics(通用)事件跟踪不起作用

google-analytics - Google Analytics - 一种通过 API 从 Query Explorer 提交查询的方法

php - 命名空间更改后的 Laravel link_to_route

php - 如何使用 PHP 路由和 .htaccess 包含 CSS/JS 和其他文件

javascript - 无效的正则表达式组

javascript - 用于捕获单词的正则表达式,无论大小写

google-analytics - 阻止引荐回我的网站

php - Laravel:whereIn 变量

php - sql查询返回时间是随机的

javascript - 我想使用 javascript regex 在句子中找到一个单词(包括特殊字符)匹配