如何从字符串的开头删除空格,但是在使用PHP的某些HTML标记内?

时间:2015-09-13 09:02:26

标签: php html preg-replace str-replace trim

说我有这个:

<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内保留空格。我该怎么做到这一点?谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式:

(?<=>)(\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);