I have this string:
ckb=199&ckb=232&ckb=200&ckb=233&ckb=201&ckb=234..
I need to create an array from it:
[0] => 199
[1] => 232
[2] => 200
[3] => 233
[4] => 201
[5] => 234
how can i do this with php?
A regex solution:
<?php
$str = "ckb=199&ckb=232&ckb=200&ckb=233&ckb=201&ckb=234";
preg_match_all("/=([^&]+|.*$)/", $str, $matches);
print_r($matches[1]);
?>
Output:
Array
(
[0] => 199
[1] => 232
[2] => 200
[3] => 233
[4] => 201
[5] => 234
)
You can use parse_str
to parse a query string. however it expects php's style of array syntax( key[]=val
) so you will need to add the square brackets:
$str = 'ckb=199&ckb=232&ckb=200&ckb=233&ckb=201&ckb=234';
$str = str_replace('=','[]=',$str);
parse_str($str, $output);
$final = $output['ckb'];
var_dump($final);
The basic idea is the use explode()
here: Example:
$string = 'ckb=199&ckb=232&ckb=200&ckb=233&ckb=201&ckb=234';
$pieces = array_map(function($piece){
$sub_piece = explode('=', $piece);
return array_pop($sub_piece);
}, explode('&', $string));
echo '<pre>';
print_r($pieces);
Should output something like:
Array
(
[0] => 199
[1] => 232
[2] => 200
[3] => 233
[4] => 201
[5] => 234
)
Sidenote: Somewhat a URL from the looks of it. If you want to modify the string, alternatively, you could also use parse_str
and make it an array instead.