简体   繁体   中英

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

Say I have this:

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

I want it to be:

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

I cannot simply use trim() as there is the <p> at the beginning. But I also can't use the str_replace() / preg_replace() as I need to retain the empty space inside This is a paragraph . How should I achieve this? Thanks!

You can use regex bellow:

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

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

PHP Code example:

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM