I have a data array containing these values:
Array
(
[id] => 1
[myid] => 9
[date] => 2014-01-30
[user] => 17
[reason] => some text here...
)
And this string which contains numbers referring to the data array indexes:
$columns = '(0) as "id",(1) as "myid",(2) as "date",(3) as "user",(4) as "reason"';
Is it possible to change the numbers enclosed in brackets, including brackets to appropriate value from the array?
I know how to work with (string) preg_replace( (array) $patterns, (array) $replacements, (string) $subject) but quite don't know how to solve this problem.
Ideally the result string could look like this:
'1' as "id",'9' as "myid",'2014-01-30' as "date",'17' as "user",'some text here...' as "reason"
The solution using preg_replace_callback and str_replace functions:
$columns = '(0) as "id",(1) as "myid",(2) as "date",(3) as "user",(4) as "reason"';
// $arr is your initial array
$result = preg_replace_callback(
"/(\(\d\)) as \"(\w+?)\",?/i",
function ($maches) use($arr){
return str_replace([$maches[1]], "'". $arr[$maches[2]]. "'", $maches[0]);
},
$columns);
print_r($result);
The output:
'1' as "id",'9' as "myid",'2014-01-30' as "date",'17' as "user",'some text here...' as "reason"
You can do it with a simple foreach loop:
$info = array(
'id' => 1,
'myid' => 9,
'date' => '2014-01-30',
'user' => 17,
'reason' => 'some text here...'
);
$columns = '(0) as "id",(1) as "myid",(2) as "date",(3) as "user",(4) as "reason"';
foreach (array_values($info) as $key => $value) {
$columns = str_replace(
'(' . $key . ')',
str_pad($value, strlen($value) + 2, "'", STR_PAD_BOTH),
$columns
);
}
echo $columns;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With