首页 > 解决方案 > 段落中第一句的 Xpath 表达式

问题描述

我正在寻找段落中第一句的 Xpath 表达式。

<p>
A federal agency is recommending that White House adviser Kellyanne Conway be 
removed from federal service saying she violated the Hatch Act on numerous 
occasions. The office is unrelated to Robert Mueller and his investigation.
</p>

结果应该是:

A federal agency is recommending that White House adviser Kellyanne Conway be 
removed from federal service saying she violated the Hatch Act on numerous 
occasions.

我尝试了几件事无济于事。

$expression = '/html/body/div/div/div/div/p//text()';

我需要使用://p[ends-with还是可能substring-before

标签: phpxmlxpathxml-parsingdomxpath

解决方案


您将无法通过 XPath 解析自然语言,但您可以获取子字符串并包括第一个句点,如下所示:

substring(/p,1,string-length(substring-before(/p,"."))+1)

请注意,如果在第一句结束之前有一个句号的缩写或其他词汇出现,如果第一句以另一种形式的标点符号结尾等,这可能不是“第一句”。


或者,更简洁:

concat(substring-before(/p, "."), ".")

信用: ThW在评论中的聪明想法。


推荐阅读