Suk*_*aul 11 php string whitespace normalize
我有一个包含多个换行符的字符串.
字符串:
This is a dummy text. I need
to format
this.
Run Code Online (Sandbox Code Playgroud)
期望的输出:
This is a dummy text. I need to format this.
Run Code Online (Sandbox Code Playgroud)
我正在使用这个:
$replacer = array("\r\n", "\n", "\r", "\t", " ");
$string = str_replace($replacer, "", $string);
Run Code Online (Sandbox Code Playgroud)
但它没有按要求/要求工作.有些单词之间没有空格.
实际上我需要用单个空格分隔的所有单词转换字符串.
Sam*_*son 22
我鼓励你使用preg_replace:
# string(45) "This is a dummy text . I need to format this."
$str = preg_replace( "/\s+/", " ", $str );
Run Code Online (Sandbox Code Playgroud)
演示: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 );
Run Code Online (Sandbox Code Playgroud)
演示:http://codepad.org/ZTX0CAGD
| 归档时间: |
|
| 查看次数: |
11299 次 |
| 最近记录: |