Reputation: 835
How do you break the string into array starting at its listing number, for example "2. " in the string.
Input:
1. new zealand 0.909991233 2. france and it territories 0.114444444 3. united states 0.99991119991 and so on
Output:
array (
"1. new zealand 0.909991233",
"2. france and it territories 0.114444444",
"3. united states 0.99991119991"
)
Thanks in advance!
PS. I know its not very easy;)
Upvotes: 0
Views: 77
Reputation: 10080
Extending from comment:
In case of two or more digits index, you can be a little more aggressive in RegExp:
array_map("trim",preg_split('#(?=\W[0-9]+\.\s+)#',"1. new zealand 0.909991233 22. france and it territories 0.114444444 333. united states 0.99991119991 and so on"))
outputs
Array
(
[0] => 1. new zealand 0.909991233
[1] => 22. france and it territories 0.114444444
[2] => 333. united states 0.99991119991 and so on
)
Upvotes: 0
Reputation: 8766
this should do it:
$str = "1. new zealand 0.909991233 2. france and it territories 0.114444444 3. united states 0.99991119991";
$pattern = '/(\d+\.\s)/i';
$replacement = '; $1';
$str = preg_replace($pattern, $replacement, $str);
$arr = explode('; ', $str);
echo implode("<br>", $arr);
Upvotes: 1
Reputation: 11460
Not too bad, one line really that does the work.
<?php
// Input
$input = "1. new zealand 0.909991233 2. france and it territories 0.114444444 3. united states 0.99991119991";
// Split the input
$ex = preg_split( "#(?=\d+\.\s+)#", $input);
// (Optional) Lose the empty result
unset( $ex[0] );
// Output
var_dump( $ex );
Upvotes: 0