Search code examples
phpstringexplode

explode string at "newline,space,newline,space" in PHP


This is the string I'm trying to explode. This string is part of a paragraph which i need to split at every "newline,space,newline,space" :

s

 1

A result from textmagic.com show it contains a \n then a space then a \n and then a space.

enter image description here

This is what I tried:

$values = explode("\n\s\n\s",$string); // 1
$values = explode("\n \n ",$string);   // 2
$values = explode("\n\r\n\r",$string); // 3

Desired output:

Array (
    [0] => s
    [1] => 1
)

but none of them worked. What's wrong here? How do I do it?


Solution

  • Just use explode() with PHP_EOL." ".PHP_EOL." ", which is of the format "newline, space, newline, space". Using PHP_EOL, you get the correct newline-format for your system.

    $split = explode(PHP_EOL." ".PHP_EOL." ", $string);
    print_r($split);
    

    Live demo at https://3v4l.org/WpYrJ