PHP:使用正则表达式从字符串中删除额外的空格 [英] PHP: remove extra space from a string using regex
本文介绍了PHP:使用正则表达式从字符串中删除额外的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用正则表达式 (preg_replace) 删除字符串末尾的多余空格?
How do I remove extra spaces at the end of a string using regex (preg_replace)?
$string = "some random text with extra spaces at the end ";
推荐答案
这里不需要正则表达式,你可以使用 rtrim
因为它更干净、更快速:
There is no need of regex here and you can use rtrim
for it, its cleaner and faster:
$str = rtrim($str);
但是如果你想要一个基于正则表达式的解决方案,你可以使用:
But if you want a regex based solution you can use:
$str = preg_replace('/\s*$/','',$str);
使用的正则表达式是 /\s*$/
\s
是任何空格的缩写字符,其中包括空格.*
是零或的量词更多$
是结束锚
\s
is short for any white space char, which includes space.*
is the quantifier for zero or more$
is the end anchor
基本上我们用空字符(''
)替换尾随的空白字符,有效地删除它们.
Basically we replace trailing whitespace characters with nothing (''
), effectively deleting them.
这篇关于PHP:使用正则表达式从字符串中删除额外的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文