我该如何使用正则表达式(preg_replace)去除字符串末尾的额外空格?
$string = "some random text with extra spaces at the end ";
$string = "some random text with extra spaces at the end ";
这里不需要使用正则表达式,你可以使用rtrim
来进行操作,它更加简洁和快速:
$str = rtrim($str);
但如果你想要一个基于正则表达式的解决方案,你可以使用:
$str = preg_replace('/\s*$/','',$str);
使用的正则表达式是/\s*$/
\s
代表任何空格字符,包括空格。*
表示重复零次或多次。$
表示匹配字符串结尾的位置。基本上,我们将尾随的空格字符替换为''
,从而有效地将它们删除。
你这里实际上不需要正则表达式,可以使用rtrim()函数。
$string = "some random text with extra spaces at the end ";
$string = rtrim($string);
另请参阅:
+
量词代替*
量词,以避免将空内容替换成空内容。 - Toto