![](/img/trans.png)
[英]php DomXPath - how to strip html tags and its contents from nodeValue?
[英]Get HTML comment from $p->nodeValue possible with DomXPath?
我有几个这样的HTML段落(总是相同的结构):
<p>
<!-- Gl. 1-4 -->
\( x(t) = x_0 · t^3 \)
[!equanchor? &id=`555`!]
</p>
我通过以下方式成功提取了555
:
$xpath = new DomXPath($dom);
$paragraphs = $xpath->query('//p');
foreach($paragraphs as $p)
{
$ptext = $p->nodeValue;
if(strpos($ptext, 'equanchor') !== false)
{
// get equation id from anchor
preg_match('/equanchor\?\s\&id=`(.*)\`/', $ptext, $matches);
$equationids[] = (int)$matches[1];
}
}
现在,我还需要HTML注释中的文本,即<!-- Gl. 1-4 -->
<!-- Gl. 1-4 -->
,但是我找不到如何为此目的使用DOM解析器(DomXPath)。 不幸的是, $p->nodeValue
或$p->textContent
确实包含注释文本。
这个答案对我没有帮助。 我尝试了“子解析器”,但无法读取$ptext
或$p
。
您可以使用comment()
XPath函数(来自使用XPath访问XML中的注释 )。
因此,在您的情况下,当您想在<p>
标记中获得注释时,只需添加行即可。
echo $dom->saveHTML($xpath->query("comment()", $p)[0]);
在您的foreach
循环中(这将获取循环中$p
元素内的comment节点)。 用[0]
得到第一个(假设只有一个)。
哪个输出...
<!-- Gl. 1-4 -->
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.