Search code examples
phpregexpreg-replacepreg-split

Replace empty spaces with ### from Text between " " in a string in PHP


I have a string like this one text more text "empty space". How can I replace the space in "empty space" and only this space with ###?


Solution

  • How about this, with no regular expressions:

    $text = 'foo bar "baz quux"';
    $parts = explode('"', $text);
    $inQuote = false;
    
    foreach ($parts as &$part) {
        if ($inQuote) { $part = str_replace(' ', '###', $part); }
        $inQuote = !$inQuote;
    }
    
    $parsed = implode('"', $parts);
    echo $parsed;