简体   繁体   English

如何从PHP中的字符串的开头和结尾删除尾随空格和“”?

[英]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. Meaningful Things可以包含[shortcodes]代码[shortcodes] ,html标签,也包含转义字符。 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM