我有一些 HTML:
<p>Lorem ipsum example laoreet. <a href="#">example</a>Cum porttitor</p>
<p>Phasellus <a href="#">gravida tempor example</a> magna</p>
我需要将 HTML 中出现的文本“example”的任何实例包裹起来,除非它位于 anchor 标记内。这样上面的内容就会变成:
<p>Lorem ipsum <span class="something">example</span> laoreet. <a href="#">example</a>Cum porttitor</p>
<p>Phasellus <a href="#">gravida tempor example</a> posuere. Fusce vitae urna eu <span class="something">example</span> magna</p>
我可以使用以下方法选择不在 anchor 标记内的段落内容:
doc.xpath('//p//text()') - doc.xpath('//p//a/text()')
我可以使用以下方法将标签包裹在另一个标签的文本内容中:
doc.search('div.some-class text()').wrap('<span class="something"></span>')
但是如何将标签包裹在该内容中的文本周围?
最佳答案
text()
Xpath 选择器也可用于匹配如下文本:
Using XPath, How do I select a node based on its text content and value of an attribute?
doc.xpath("//p//text()='example'")
但我认为这行不通:
doc.search("div.some-class text()='example'").wrap('<span class="something"></span>')
关于html - 使用 Nokogiri 包裹不在 anchor 标记内的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18230990/