I get the format of this {1}1{2}3{3}6
string in php and I want to make the numbers in curly braces to be the indexes of array and the value stored on the indexes will be the value after the curly braces. So that I can easily apply foreach
to enter the values in database.
Output Array should be like:
array([1]=>1,[2]=>3,[3]=>6)
$result = [];
$data = '{1}1{2}3{3}6';
preg_match_all('/\{(\d+)\}\s*(\d+)/', $data, $m);
foreach ($m[1] as $i => $key) {
$result[$key] = $m[2][$i];
}
You can try it with regex "Regular expression" as follows:
<?php
$string="{1}1{2}3{3}6";
//Define the regex
$regex = "/{([a-zA-Z0-9_]*)}\s*([a-zA-Z0-9_]*)/";
preg_match_all($regex, $string, $matches);
//Temporary array to store the data
$arry = array();
foreach($matches[1] as $key => $value){
$arry[$value] = $matches[2][$key];
}
var_dump($arry);
?>
[Proof of concept]
array(3) {
[1]=> string(1) "1"
[2]=> string(1) "3"
[3]=> string(1) "6"}
Try:
$str = '{1}1{2}3{3}6';
$arr = explode("}", substr(str_replace("{", "}", $str), (strlen($str)-1)*-1));
$arr = array_map(function ($v){ global $arr; return $arr[$v+1]; }, array_flip(array_intersect_key($arr, array_flip(array_filter(array_keys($arr), function ($v){ return !($v & 1); })))));