PHP / XPath:查找“开始”的文本节点一个特定的字符串? [英] PHP/XPath: find text node that "starts with" a particular string?
问题描述
我需要知道一个特定的字符串是否存在于一个特定的节点中。例如,我需要知道HTML DOM中的第三段中是否存在快速褐色狐狸。我正在使用PHP的DOMXPath。任何建议?
I need to know if a particular string exist in a particular node. For example, I need to know if "quick brown fox" exist in the, say, 3rd paragraph of an HTML DOM. I'm using PHP's DOMXPath. Any suggestions?
推荐答案
尝试以下操作:
示例来源:
$html = <<< HTML
<body>
<p>the dead brown fox</p>
<p>the slow brown fox</p>
<p>the quick brown fox</p>
<p>the crawling brown fox</p>
</body>
HTML;
代码
$dom = new DOMDocument;
$dom->loadXml($html);
$xp = new DOMXPath($dom);
echo $xp->evaluate('count(/body/p[3][contains(., "quick")])');
XPath转换为 count body元素下面的第三个p元素包含文本节点值quick。如果搜索的项存在于节点值的任何位置,这将返回1或0。
The XPath translates to count the 3rd p element below the body element that contains a text node value of "quick". This will return 1 or 0 if the searched term exists anywhere within the node value.
如果您需要知道节点值是否以开头一个特定的短语,使用启动功能。
If you need to know if the node value starts with a specific phrase, use the starts-with function instead.
PHP的DOM扩展程序支持XPath 1.0。
PHP's DOM extension supports XPath 1.0.
您也可以通过常规API进行XPath: / p>
You can also do it without XPath through the regular API:
$dom = new DOMDocument;
$dom->loadXml($html);
$thirdPara = $dom->getElementsByTagName('p')->item(2);
echo strpos($thirdPara->nodeValue, 'the quick') === 0 ? 1 : 0;
getElementsByTagName
方法通过标签名称查找所有元素。 项目
调用返回第三个这些元素(从零开始)。 strpos
函数查找字符串第一次出现的位置。上述代码片段的结果将再次为1(如果节点值不以快速开头,则为0)。
The getElementsByTagName
method finds, who would have thought, all elements by tag name. The item
call returns the third of those elements (zero-based). The strpos
function finds the position of first occurrence of a string. The result of the snippet above would be 1 again (or 0 if the node value does not start with 'the quick'.
这篇关于PHP / XPath:查找“开始”的文本节点一个特定的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!