php removing excess whitespace

后端 未结 4 1392
天涯浪人
天涯浪人 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: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.

提交回复
热议问题