繁体   English   中英

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

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

如果

$text = '           MEANINGFUL THINGS GO HERE         ';

我怎样才能得到

$cleanText = 'MEANINGFUL THINGS GO HERE';

我知道以下将删除所有的空格

$text=trim($text);

但是如何将实际逃逸的空间纳入装饰呢?

Meaningful Things可以包含[shortcodes]代码[shortcodes] ,html标签,也包含转义字符。 我需要保留这些。

任何帮助,将不胜感激。 谢谢!

$text = '           MEANINGFUL THINGS GO HERE         ';

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

var_dump( $text );

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

额外的测试

$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