我想在 PHP 中使用 XPath 选择最接近表单上方的标题元素(无论是 h1、h2、h3、h4、h5 还是 h6)。
<h2>Foo</h2>
<h3>Bar</h3>
<form>
<input />
</form>
上面的示例应返回 h3 (Bar),因为它最接近表单。
<h4>Kee</h4>
<form>
<input />
</form>
另一方面,此示例应返回 h4 (Kee),因为它最接近。
此查询(来自 https://stackoverflow.com/a/2216795/4391251)仅适用于 h2 标签。我可以为 h1、h3、h4、h5 等修改它,但我想要一个包罗万象的查询。
$headings = $xpath->query('((//form)[2]/ancestor::*/h2[.!=""])[last()]');
基本上我想要这样的东西
$headings = $xpath->query('((//form)['.$i.']/ancestor::*/[h2 or h3][.!=""])[last()]');
除此之外,它不会返回任何结果,也不会(基于 https://stackoverflow.com/a/7995095/4391251)
$headings = $xpath->query('((//form)['.$i.']/ancestor::*/[self::h2 or self::h3][.!=""])[last()]');
什么查询将给出所需的结果?
你可以尝试这样的事情:
$xpath->query('//form['.$i.']/preceding-sibling::*[self::h2 or self::h3][1]')
基本上,xpath 获取类型为 <h2>
或 <h3>
的form[i]
的第一个前置同级(或者其他什么,只需在 xpath 谓词中根据需要列出所有其他元素)。
在形式之前取拳头h
//form/preceding::*[starts-with(name(),'h')][1]
/html/body/*[starts-with(name(),'h')]