Reputation: 55
$string="112*1/25 5*112/20 456*8/20 2*569/20 156*3/40 9*789/20";
I am trying to split string after second white space. How to achieve this? I tried using following approach.
$my_array=preg_match('/^([^ ]+ +[^ ]+) +(.*)$/', '$string', $split);
I am getting output as 1. My desired output must be look like below
$split=array([0]=>112*1/25 5*112/20 [1]=>456*8/20 2*569/20 [2]=>156*3/40 9*789/20);
Upvotes: 1
Views: 1740
Reputation: 266
<?php
$string="112*1/25 5*112/20 456*8/20 2*569/20 156*3/40 9*789/20";
$array1=(explode(" ", $string));
$new_array=array_chunk($array1, 2);
$n=count($new_array);
for ($i=0; $i < $n ; $i++) {
$str_arr[] = implode(" ", $new_array[$i]);
}
print_r($str_arr);
?>
Upvotes: 1
Reputation: 7703
You can use preg_match_all.
$string="112*1/25 5*112/20 456*8/20 2*569/20 156*3/40 9*789/20";
$r = preg_match_all('~[^ ]+ [^ ]+~',$string, $match);
echo '<pre>';
var_dump($match[0]);
Output:
array(3) {
[0]=>
string(17) "112*1/25 5*112/20"
[1]=>
string(17) "456*8/20 2*569/20"
[2]=>
string(17) "156*3/40 9*789/20"
}
Upvotes: 1
Reputation: 6388
You can try this
$string="112*1/25 5*112/20 456*8/20 2*569/20 156*3/40 9*789/20";
$arr = array_chunk(explode(' ',$string),2);
$res = array_map(function($v){ return implode(' ',$v);}, $arr);
Working example :- https://3v4l.org/FLTom
Upvotes: 1
Reputation: 1232
You can try it:
$string="112*1/25 5*112/20 456*8/20 2*569/20 156*3/40 9*789/20";
$split = array_map(
function($value) {
return implode(' ', $value);
},
array_chunk(explode(' ', $string), 2)
);
var_dump($split);
Upvotes: 2