我有一个包含多个换行符的字符串。
字符串:
This is a dummy text. I need
to format
this.
期望的输出:
This is a dummy text. I need to format this.
我用这个:
$replacer = array("\r\n", "\n", "\r", "\t", " ");
$string = str_replace($replacer, "", $string);
但它没有按照要求/要求运作。有些词在它们之间没有空格。
实际上我需要将所有用单个空格分隔的单词转换为字符串。
答案 0 :(得分:22)
我建议您使用preg_replace
:
# string(45) "This is a dummy text . I need to format this."
$str = preg_replace( "/\s+/", " ", $str );
演示:http://codepad.org/no6zs3oo
您可能已在第一个示例的" . "
部分中注意到。紧跟着标点符号的空格应该可以完全删除。快速修改允许:
$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 );