如何删除尾随空格和“ "从 PHP 中的字符串的开头和结尾? [英] How to remove trailing white spaces and " " from the start and end of a string in PHP?

查看:40
本文介绍了如何删除尾随空格和“ "从 PHP 中的字符串的开头和结尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果

$text = '           MEANINGFUL THINGS GO HERE         ';

我如何获得

$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 可以包含 [shortcodes]、html 标签以及转义字符.我需要保存这些.

Meaningful Things can contain [shortcodes], html tags, and also escaped characters. 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"

附加测试

$text = '       S       S    ';
-->
string(24) "S       S"

$text = '                  ';
-->
string(0) ""

$text = '         &nbst; &nbst;      ';
-->
string(18) "&nbst; &nbst;"

这篇关于如何删除尾随空格和“ "从 PHP 中的字符串的开头和结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆