我有一个带有多个换行符的字符串。
字符串:
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);
但它没有按预期/要求工作。有些单词之间没有空格。
实际上我需要转换字符串,所有单词都用单个空格分隔。
我鼓励你使用preg_replace
:
# string(45) "This is a dummy text . I need to format this."
$str = preg_replace( "/\s+/", " ", $str );
Demo: http://codepad.org/no6zs3oo 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 );
Demo: http://codepad.org/ZTX0CAGD http://codepad.org/ZTX0CAGD
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)