Mohammad
Mohammad

Reputation: 7418

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!

Upvotes: 4

Views: 6037

Answers (3)

James Anderson Jr.
James Anderson Jr.

Reputation: 806

Regarding @Esailija's accepted answer…

What about  ,  ,  ,  ,  ,  , etc… Wouldn't this be more complete?

$txt = preg_replace('/(^((\&((nbsp)|(((hair)|(very)?(thin))sp(ace)?)|(\#820(1|2)))\;)|(\x{2009}\|\x{200a})|(\s))+|((\&((nbsp)|(((hair)|(very)?(thin))sp(ace)?)|(\#820(1|2)))\;)|(\x{2009}\|\x{200a})|(\s))+$)/imu', '', $txt);

Upvotes: 0

Esailija
Esailija

Reputation: 140230

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

Upvotes: 8

Ashley Strout
Ashley Strout

Reputation: 6258

Also run an html_entity_decode on this, then trim:

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

Upvotes: 3

Related Questions