Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 998
Mohammad Avatar asked Oct 25 '25 18:10

Mohammad


2 Answers

$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;"
like image 98
Esailija Avatar answered Oct 27 '25 08:10

Esailija


Also run an html_entity_decode on this, then trim:

$text=trim(html_entity_decode($text));
like image 43
Ashley Strout Avatar answered Oct 27 '25 07:10

Ashley Strout