如何使用 PHP 从字符串开头但在某些 HTML 标签内删除空 space?

How can I remove empty space from the beginning of strings but inside some HTML tags using PHP?

假设我有这个:

<p>  This is a paragraph.</p><p>&nbsp;This is another paragraph.</p>

我希望它是:

<p>This is a paragraph.</p><p>This is another paragraph.</p>

我不能简单地使用 trim() 因为开头有 <p>。但我也不能使用 str_replace()/preg_replace(),因为我需要在 This is a paragraph 中保留空的 space。我应该如何实现这一目标?谢谢!

您可以使用下面的正则表达式:

(?<=>)(\s|&nbsp;)*|(\s|&nbsp;)*(?=<\/)

https://regex101.com/r/fZ3oQ3/2

PHP 代码示例:

$re = "/(?<=>)(\s|&nbsp;)*|(\s|&nbsp;)*(?=<\/)/"; 
$str = "<p>  This is a paragraph.</p><p>&nbsp;This is another paragraph.</p>\n"; 
$subst = ""; 

$result = preg_replace($re, $subst, $str);