php removing excess whitespace

后端 未结 4 1393
天涯浪人
天涯浪人 2020-12-16 14:55

I\'m trying to remove excess whitespace from a string like this:

hello        world

to

相关标签:
4条回答
  • 2020-12-16 15:36

    There is an example on how to strip excess whitespace in the preg_replace documentation

    0 讨论(0)
  • 2020-12-16 15:39
    $str = 'Why   do I
              have  so much white   space?';
    
    $str = preg_replace('/\s{2,}/', ' ', $str);
    
    var_dump($str); // string(34) "Why do I have so much white space?"
    

    See it!

    You could also use the + quantifier, because it always replaces it with a . However, I find {2,} to show your intent clearer.

    0 讨论(0)
  • 2020-12-16 15:40

    With a regexp :

    preg_replace('/( )+/', ' ', $string);
    

    If you also want to remove every multi-white characters, you can use \s (\s is white characters)

    preg_replace('/(\s)+/', ' ', $string);
    
    0 讨论(0)
  • 2020-12-16 15:55

    Not a PHP expert, but his sounds like a job for REGEX....

    <?php
    $string = 'Hello     World     and Everybody!';
    $pattern = '/\s+/g';
    $replacement = ' ';
    echo preg_replace($pattern, $replacement, $string);
    ?>
    

    Again, PHP is not my language, but the idea is to replace multiple whitespaces with single spaces. The \s stands for white space, and the + means one or more. The g on the end means to do it globally (i.e. more than once).

    0 讨论(0)
提交回复
热议问题