我有几个HTML页面的代码看起来像这样:
<!-- ID: 123456 -->
我需要的是一个PHP脚本,可以拉那个ID号。我尝试了以下操作:
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.";
}`
总是给出"No match found",没有错误报告。我也尝试了preg_match_all和相同的结果。我发现唯一的工作是创建一个基于空间的数组,但这是非常耗时和浪费处理器电源。
作为参考,我已经看过并尝试了这些页面上的每一个建议:
用一个或多个空格或制表符分隔字符串
http://php.net/manual/en/function.preg-split.php如何提取html评论和所有的html包含的节点?
试试这个:
<!-- ID: (['w ]+) -->
这将搜索示例中提到的所有文字,并且提取数字ID。你可以通过编号来获取它组。
PS:使用转义
要从结构化数据(如HTML, XML, Json…)中提取信息,请使用正确的解析器(DOMDocument和DOMXPath来查询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
首先将HTML文件视为文本文件,因为您只想从. HTML文件中读取一些文本。
test.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>This is a test HTML page<p>
<!-- ID: 123456 -->
</body>
</html>
从HTML文件中获取ID的PHP脚本
<?php
$fileName = 'test.html';
$content = file_get_contents($fileName);
$start = '<!-- ID:';
$end = '-->';
function getBetween($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
echo str_replace(' ', '', getBetween($content,$start,$end));
?>