我如何删除空白的空间,从字符串的开始,但在一些HTML标签使用PHP


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内部的空白空间。我该如何做到这一点?谢谢!

你可以在下面使用正则表达式:

(?<=>)('s|&nbsp;)*|('s|&nbsp;)*(?=<'/)
https://regex101.com/r/fZ3oQ3/2

代码示例:
$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);