Reputation: 241
I have a long string say "123~456!!!789~012!!!345~678!!!901~234!!!567~890!!!1234~5678". I have used to types of delimiter in this string ~ and !!! . Can anyone suggest me an efficient way to explode(split) this string to a 2d array. Example:
$txt = "123~456!!!789~012!!!345~678!!!901~234!!!567~890!!!1234~5678".
The 2D array after exploding/splitting.
array[0][0] = 123 ; array[0][1] = 456 ;
array[1][0] = 789 ; array[1][1] = 012 ;
array[2][0] = 345 ; array[2][1] = 678 ;
array[3][0] = 901 ; array[3][1] = 234;
array[4][0] = 567 ; array[4][1] = 890;
array[5][0] = 1234 ; array[5][1] = 5678;
Thanks. :)
Upvotes: 2
Views: 349
Reputation: 9351
Have a look at preg_split()
function.
$txt = "123~456!!!789~012!!!345~678!!!901~234!!!567~890!!!1234~5678";
$array = preg_split ('/!!!|~/', $txt);
print_r($array);
Output:
Array ( [0] => 123 [1] => 456 [2] => 789 [3] => 012 [4] => 345 [5] => 678 [6] => 901 [7] => 234 [8] => 567 [9] => 890 [10] => 1234 [11] => 5678 )
Upvotes: 0
Reputation: 1572
$txt = "123~456!!!789~012!!!345~678!!!901~234!!!567~890!!!1234~5678".
$firstSplit = explode("!!!",$txt);
$newArray = array();
for($i=0;$i<sizeof($firstSplit);$i++){
$secondSplit = explode("~",$firstSplit[$i]);
for($j=0;$j<sizeof($secondSplit);$j++){
$newArray[$i][] = $secondSplit[$j];
}
}
I think something like that should work.
Upvotes: 0
Reputation: 28941
This is all it takes:
foreach(explode("!!!",$txt) AS $key => $subarray) {
$array[$key] = explode("~",$subarray);
}
print_r($array);
Quick and efficient, and you'll get your two-dimensional array.
Upvotes: 0
Reputation: 173642
You could use preg_match_all()
using PREG_SET_ORDER
and then map each item to eliminate the zero index:
$txt = "123~456!!!789~012!!!345~678!!!901~234!!!567~890!!!1234~5678";
if (preg_match_all('/(\d+)~(\d+)/', $txt, $matches, PREG_SET_ORDER)) {
$res = array_map(function($item) {
return array_slice($item, 1);
}, $matches);
print_r($res);
}
Alternatively, use a double explode()
:
$res = array_map(function($item) {
return explode('~', $item, 2);
}, explode('!!!', $txt));
print_r($res);
Upvotes: 0