PHP: remove extra space from a string using regex

独自空忆成欢 提交于 2021-02-07 06:29:05

问题


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      ";

回答1:


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);

The regex used is /\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.




回答2:


You don't really need regex here, you can use the rtrim() function.

$string = "some random text with extra spaces at the end      ";
$string = rtrim($string);

Code on ideone


See also :

  • trim()
  • ltrim()



回答3:


You can use rtrim




回答4:


You can use trim() to do this:

http://php.net/manual/en/function.trim.php



来源:https://stackoverflow.com/questions/3763439/php-remove-extra-space-from-a-string-using-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!