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

孤街浪徒 提交于 2019-12-10 21:05:13

问题


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!


回答1:


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



回答2:


Also run an html_entity_decode on this, then trim:

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


来源:https://stackoverflow.com/questions/10603527/how-to-remove-trailing-white-spaces-and-nbsp-from-the-start-and-end-of-a-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!