PHP / HTML评论标签

时间:2015-09-22 20:35:54

标签: php html regex preg-match

我有几个HTML页面,其代码如下所示:

<!-- ID: 123456 -->

我需要的是一个可以提取该ID号的PHP脚本。我尝试过以下方法:

if (preg_match('#^<!--(.*?)-->#i', $output)) {
                echo "A match was found.";
            } else {
                echo array_flip(get_defined_constants(true)['pcre'])[preg_last_error()];
                echo "No match found.";
            }`

总是给出“找不到匹配项”,没有报告错误。我也试过了preg_match_all和相同的结果。我发现的唯一工作就是创建一个基于空格的数组,但这非常耗时并浪费处理器能力。

作为参考,我在这些页面上查看并尝试了几乎所有建议:

Explode string by one or more spaces or tabs

http://php.net/manual/en/function.preg-split.php

How to extract html comments and all html contained by node?

3 个答案:

答案 0 :(得分:1)

试试这个怎么样:

<!-- ID: ([\w ]+) -->
  

这将搜索示例中提到的所有文字,以及   提取数字ID。您可以在编号的帮助下获取它   基。

PS:使用转义。

答案 1 :(得分:1)

要从结构化数据中提取信息(如HTML,XML,Json ...),请使用正确的解析器(DOMDocumentDOMXPath来查询DOM树):

$html = <<<'EOD'
<script>var a='<!-- ID: avoid_this --> and that <!-- ID: 666 -->';</script>
blahblah<!-- ID: 123456 -->blahblah
EOD;

$query = '//comment()[starts-with(., " ID: ")]';

$dom = new DOMDocument;
$dom->loadHTML($html);
$xp = new DOMXPath($dom);

$nodeList = $xp->query($query);

foreach ($nodeList as $node) {
    echo substr($node->textContent, 5, -1);
}

随后使用is_numeric或正则表达式检查结果。您可以注册自己的php函数并将其包含在xpath查询中:http://php.net/manual/en/domxpath.registerphpfunctions.php

答案 2 :(得分:-1)

首先将HTML文件视为文本文件,因为您只想从.html文件中读取一些文本。

<强>的test.html

/s

从HTML文件中获取ID的PHP脚本

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<p>This is a test HTML page<p>
<!-- ID: 123456 -->
</body>
</html>
相关问题