简体   繁体   中英

How to remove trailing white spaces and “ ” from the start and end of a string in PHP?

If

$text = '           MEANINGFUL THINGS GO HERE         ';

How can I get

$cleanText = 'MEANINGFUL THINGS GO HERE';

I know the following will remove all the white spaces

$text=trim($text);

but how can incorporate actual escaped space into the trim as well?

Meaningful Things can contain [shortcodes] , html tags, and also escaped characters. I need these to be preserved.

Any help would be appreciated. Thanks!

$text = '           MEANINGFUL THINGS GO HERE         ';

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

var_dump( $text );

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

additional tests

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

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

$text = '         &nbst; &nbst;      ';
-->
string(18) "&nbst; &nbst;"

还要对此运行html_entity_decode ,然后修剪:

$text=trim(html_entity_decode($text));

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