使用 DomXPath 可以从 $p->nodeValue 获取 HTML 评论吗?
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 -->
,但我找不到如何使用DOM 用于此目的的解析器 (DomXPath)。不幸的是,$p->nodeValue
和 $p->textContent
都包含评论文本。
This answer 没有帮助我。我尝试了 "sub parser" 但它无法读取 $ptext
或 $p
.
您可以使用 comment()
XPath 函数(来自 Accessing Comments in XML using XPath)。
所以在你的情况下,当你想在 <p>
标签中获得评论时,你可以只添加行...
echo $dom->saveHTML($xpath->query("comment()", $p)[0]);
在您的 foreach
循环中(这会在您的循环中获取 $p
元素内的评论节点)。使用 [0]
得到第一个(假设只有一个)。
哪个输出...
<!-- Gl. 1-4 -->
我有几个这样的 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 -->
,但我找不到如何使用DOM 用于此目的的解析器 (DomXPath)。不幸的是,$p->nodeValue
和 $p->textContent
都包含评论文本。
This answer 没有帮助我。我尝试了 "sub parser" 但它无法读取 $ptext
或 $p
.
您可以使用 comment()
XPath 函数(来自 Accessing Comments in XML using XPath)。
所以在你的情况下,当你想在 <p>
标签中获得评论时,你可以只添加行...
echo $dom->saveHTML($xpath->query("comment()", $p)[0]);
在您的 foreach
循环中(这会在您的循环中获取 $p
元素内的评论节点)。使用 [0]
得到第一个(假设只有一个)。
哪个输出...
<!-- Gl. 1-4 -->