Reputation: 444
I have been playing arround with this function, basically I want to "separate" a string using \n character but for some reason on this case it generates 3 items:
$breaks = explode("\n","\n\n");
My goal for this case is just an array with 2 items.
Upvotes: 0
Views: 312
Reputation: 1366
The last occurrence of the delimiter in your string delimits an empty string, e. g.
var_dump( explode("\n", "\n") );
will return an array with two empty elements, the first slot coming from before the delimiter occurrence, the second value from behind it:
array(2) {
[0] =>
string(0) ""
[1] =>
string(0) ""
}
So you just have to make sure that your string does not end with a delimiter in order to not get an empty element at the end of the array.
Upvotes: 2
Reputation: 7713
Is the actual problem to select lines of text separated by \n, \r, \r\n or \n\n ?
If different data sources (Win, Linux) are available, different separators must be considered. For this, preg_split is ideal. An example:
$text = " Line1 \n Line2 \r\n Line3 \r Line4 \n\n Line5 \n";
$arr = preg_split('~\R~', $text, null, PREG_SPLIT_NO_EMPTY);
echo "<pre>".var_export($arr,true)."</pre>";
Output
array (
0 => ' Line1 ',
1 => ' Line2 ',
2 => ' Line3 ',
3 => ' Line4 ',
4 => ' Line5 ',
)
Upvotes: 0
Reputation: 48031
It looks like you want to match strings of zero or greater length that contain non-vertical-space characters which are followed by a vertical space character.
Code: (Demo)
$text = "\n\n";
var_export(preg_match_all('~\V*(?=\R)~', $text, $matches) ? $matches[0] : []);
There will be several patterns and functions to achieve the desired result, but this one seems pretty straight forward to me.
As for explaining your current output, imagine splitting the outward projections on one of your hands based on the gaps between them. There are four gaps, so your finger count will be 5 (barring any birth defects or mishaps).
Upvotes: 1
Reputation: 28554
You can do it by iterate the string with, check Demo
$string = "\n\n";
$result = [];
$str = "";
$index = 0;
while($index < strlen($string)){
if($string[$index] == "\n"){
$result[] = $str;
$str = "";
}else{
$str .= $string[$index];
}
$index++;
}
if($str){
$result[] = $str;
}
var_dump($result);
Upvotes: 1