Remove extra spaces but not space between two words

前端 未结 6 1942
忘掉有多难
忘掉有多难 2020-12-06 00:54

I want to remove extra spaces present in my string. I have tried trim,ltrim,rtrim and others but non of them are working and even trie

6条回答
  •  醉话见心
    2020-12-06 01:10

    OK, so you want to trim all whitespace from the end of the string and excess whitespace between words.

    You can do this with a single regex:

    $result = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $subject);
    

    Explanation:

    ^\s+      # Match whitespace at the start of the string
    |         # or
    \s+$      # Match whitespace at the end of the string
    |         # or
    \s+(?=\s) # Match whitespace if followed by another whitespace character
    

    Like this (example in Python because I don't use PHP):

    >>> re.sub(r"^\s+|\s+$|\s+(?=\s)", "", "  Hello\n   and  welcome to  India   ")
    'Hello and welcome to India'
    

提交回复
热议问题