<\/script>')

How to remove trailing spaces and "& nbsp;" from the beginning and end of a line in PHP?

If

$text = '    &nbsp;    &nbsp; MEANINGFUL THINGS GO HERE &nbsp;&nbsp;     &nbsp;';

How can I get

$cleanText = 'MEANINGFUL THINGS GO HERE';

I know the following will remove all spaces

$text=trim($text);

but how can you include the actual shielded space in the crop?

Meaningful Thingsmay contain tags [shortcodes], html, as well as escaped characters. I need them to be saved.

Any help would be greatly appreciated. Thank!

+3
source share
2 answers
$text = '    &nbsp;    &nbsp; MEANINGFUL THINGS GO HERE &nbsp;&nbsp;     &nbsp;';

$text = preg_replace( "#(^(&nbsp;|\s)+|(&nbsp;|\s)+$)#", "", $text );

var_dump( $text );

//string(25) "MEANINGFUL THINGS GO HERE"

additional tests

$text = '    &nbsp;  S  &nbsp;&nbsp;&nbsp;  S   &nbsp;';
-->
string(24) "S  &nbsp;&nbsp;&nbsp;  S"

$text = '    &nbsp;    &nbsp;&nbsp;&nbsp;     &nbsp;';
-->
string(0) ""

$text = '    &nbsp;    &nbst;&nbsp;&nbst;     &nbsp;';
-->
string(18) "&nbst;&nbsp;&nbst;"
+8
source

Also run html_entity_decode , then crop:

$text=trim(html_entity_decode($text));
+3
source

All Articles