node_man
node_man

Reputation: 1449

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?

Upvotes: 1

Views: 1066

Answers (2)

Qirel
Qirel

Reputation: 26460

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

Upvotes: 2

Rahat Hameed
Rahat Hameed

Reputation: 432

Using preg_split() to explode() by multiple delimiters in PHP

Just a quick note here. To explode() a string using multiple delimiters in PHP you will have to make use of the regular expressions. Use pipe character to separate your delimiters.

$string = "\n\ranystring"
$chunks = preg_split('/(de1|del2|del3)/',$string,-1, PREG_SPLIT_NO_EMPTY);

// Print_r to check response output.
echo '<pre>';
print_r($chunks);
echo '</pre>';

PREG_SPLIT_NO_EMPTY – To return only non-empty pieces.

Upvotes: 0

Related Questions