【问题标题】:Replace Multiple Spaces and Newlines with only one space in PHP在 PHP 中用一个空格替换多个空格和换行符
【发布时间】:2012-06-04 07:54:44
【问题描述】:

我有一个包含多个换行符的字符串。

字符串:

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

但它没有按预期/要求工作。有些单词之间没有空格。

实际上我需要将字符串中的所有单词用单个空格分隔。

【问题讨论】:

    标签: php string whitespace normalize


    【解决方案1】:

    我鼓励你使用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 );
    

    演示:http://codepad.org/ZTX0CAGD

    【讨论】:

    • 是的。知道了。再次感谢!一个问题@JonathanSampson。我在哪里可以详细了解这个正则表达式?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 2013-11-25
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 2012-01-11
    相关资源
    最近更新 更多