Search code examples
phpregexstringalgorithmimplode

How to implode newlines/break lines to a space?


How to implode newlines/break lines to a space?

given these $strings:

The quick brown
fox jumps 
over the lazy
dog

imploding those strings with a blank space

$keys = implode(' ', array_keys($strings));

I have this:

The quick brownfox jumpsover the lazydog

And I'm trying to have this:

The quick brown fox jumps over the lazy dog

Any lights? Thank you.


Solution

  • You may want to use preg_replace for this instead of explode/implode:

    $s = 'The quick brown
    fox jumps
    over the lazy
    dog';
    
    $s = preg_replace('#[\r\n]#', ' ', $s);
    
    echo $s;
    

    Output:

    The quick brown fox jumps over the lazy dog