Remove extra spaces but not space between two words

前端 未结 6 1922
忘掉有多难
忘掉有多难 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:02

    If You remove single space between word. try it

    trim(str_replace(' ','','hello word'));

    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-12-06 01:10

    Try this, this will also remove all &nbsp

    $node3 = htmlentities($node3, null, 'utf-8');
    $node3 = str_replace(" ", "", $node3);
    $node3 = html_entity_decode($node3);
    
    $node3 = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $node3);
    
    0 讨论(0)
  • 2020-12-06 01:13

    If you want to remove multiple spaces within a string you can use the following:

    $testStr = "                  Hello Welcome
                             to India    ";
    $ro = trim(preg_replace('/\s+/', ' ', $testStr));
    
    0 讨论(0)
  • 2020-12-06 01:22

    I Think what we are supposed to do here is we should not look for 1 space we should look for consecutive two spaces and then make it one. So this way it would not replace the space between the text and also remove any other space.

    $new_string= str_replace(' ', ' ', $old_string)

    for more on Str Replace

    0 讨论(0)
  • 2020-12-06 01:23
    $cleanStr = trim(preg_replace('/\s\s+/', ' ', str_replace("\n", " ", $str)));
    
    0 讨论(0)
提交回复
热议问题