Replace Multiple Spaces and Newlines with only one space in PHP

余生长醉 提交于 2019-12-04 01:27:47

I would encourage you to use preg_replace:

# string(45) "This is a dummy text . I need to format this."
$str = preg_replace( "/\s+/", " ", $str );

Demo: http://codepad.org/no6zs3oo

You may have noted in the " . " portion of the first example. Spaces that are immediately followed by punctuation should probably be removed entirely. A quick modification permits this:

$patterns = array("/\s+/", "/\s([?.!])/");
$replacer = array(" ","$1");

# string(44) "This is a dummy text. I need to format this."
$str = preg_replace( $patterns, $replacer, $str );

Demo: http://codepad.org/ZTX0CAGD

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