选择nodeValue,但排除子元素


Select nodeValue but exclude child elements

假设我有这样的代码:

<p dataname="description">
Hello this is a description. <a href="#">Click here for more.</a>
</p>

如何选择p的nodeValue,但不包括a及其内容?

我当前的代码:

$result = $xpath->query("//p[@dataname='description'][not(self::a)]");

我通过$result->item(0)->nodeValue; 选择它

只需在查询中添加/text()就可以完成

$result = $xpath->query("//p[@dataname='description'][not(self::a)]/text()");

不确定PHP的XPath是否支持这一点,但这个XPath在Scrapy(基于Python的抓取框架)中帮了我一把:

$xpath->query('//p[@dataname='description']/text()[following-sibling::a]')

如果这不起作用,请尝试Kristoffers解决方案,或者您也可以使用regex解决方案。例如:

$output = preg_replace("~<.*?>.*?<.*?>~msi", '', $result->item(0)->nodeValue);

这将删除任何包含任何内容的HTML标记,不包括未被HTML标记封装的文本。