PHP:使用正则表达式从字符串中删除多余的空格

Zeb*_*bra 7 php regex string whitespace

如何使用regex(preg_replace)删除字符串末尾的额外空格?

$string = "some random text with extra spaces at the end      ";
Run Code Online (Sandbox Code Playgroud)

cod*_*ict 17

这里不需要正则表达式,你可以使用rtrim它,它更干净,更快:

$str = rtrim($str);
Run Code Online (Sandbox Code Playgroud)

但是如果你想要一个基于正则表达式的解决方案,你可以使用:

$str = preg_replace('/\s*$/','',$str);
Run Code Online (Sandbox Code Playgroud)

使用的正则表达式是 /\s*$/

  • \s 是任何空白字符的缩写,包括空格.
  • * 是零或更多的量词
  • $ 是最终的锚点

基本上我们用nothing('')替换尾随空白字符,有效地删除它们.


Col*_*ert 10

你真的不需要正则表达式,你可以使用rtrim()函数.

$string = "some random text with extra spaces at the end      ";
$string = rtrim($string);
Run Code Online (Sandbox Code Playgroud)

关于ideone的代码


也可以看看 :