Replace excess whitespaces and line-breaks with PHP?

后端 未结 10 1735
你的背包
你的背包 2020-12-07 20:25
$string = \"My    text       has so    much   whitespace    




Plenty of    spaces  and            tabs\";

echo preg_replace(\"/\\s\\s+/\", \" \", $string);
         


        
10条回答
  •  借酒劲吻你
    2020-12-07 21:25

    Had the same problem when passing echoed data from PHP to Javascript (formatted as JSON). The string was peppered with useless \r\n and \t characters that are neither required nor displayed on the page.

    The solution i ended up using is another way of echoing. That saves a lot of server resources compared to preg_replace (as it is suggested by other people here).


    Here the before and after in comparison:

    Before:

    echo '
    
    Example Example
    ';

    Output:

    \r\n\r\n\tExample\r\n\tExample\r\n\r\n


    After:

    echo 
    '
    ', 'Example', 'Example', '
    ';

    Output:

    ExampleExample


    (Yes, you can concatenate echo not only with dots, but also with comma.)

提交回复
热议问题