如何在 PHP 中定位非空 p 元素?

问题描述 投票:0回答:1

我正在为我的 WordPress 网站开发一个插件。我想选择所有非空段落元素。

这是我的代码:



function my_php_custom_function($content){

 // Create a new DOMDocument instance
 $dom = new DOMDocument();

 // Load the HTML content into the DOMDocument
 $dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

 // Create a DOMXPath object to query the DOM
 $xpath = new DOMXPath($dom);

 // Find all non-empty p elements in the content
 $p_elements = $xpath->query('//p[string-length(normalize-space()) > 0]');
}


add_filter('the_content','my_php_custom_function')

$p_elements
在这个变量中,我也得到了我刚刚通过按 Enter 键创建的那些段落。当我检查 DOM 时,它显示为
<p>&nbsp;</p>

php wordpress wordpress-plugin-creation
1个回答
0
投票

您可能会为您的内容使用某种所见即所得编辑器,在某些情况下会生成仅包含

&nbsp;

的元素

要获取非空 P 元素并忽略仅包含

&nbsp;
的 P 元素,您的 XPath 可能如下所示:

//p[normalize-space() and not(normalize-space(.) = '&nbsp;')]

未经测试,但格式正确。

© www.soinside.com 2019 - 2024. All rights reserved.