Replace Multiple Spaces and Newlines with only one space in PHP

前端 未结 1 1624
深忆病人
深忆病人 2021-02-14 06:06

I have a string with multiple newlines.

The String:

This is         a dummy text.               I need              




to                                       


        
相关标签:
1条回答
  • 2021-02-14 06:30

    I would encourage you to use preg_replace:

    # string(45) "This is a dummy text . I need to format this."
    $str = preg_replace( "/\s+/", " ", $str );
    

    Demo: http://codepad.org/no6zs3oo

    You may have noted in the " . " portion of the first example. Spaces that are immediately followed by punctuation should probably be removed entirely. A quick modification permits this:

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

    Demo: http://codepad.org/ZTX0CAGD

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