what I need to do is to parse a string similar to this:
{a}3{/a}*{b}4{/b}
or this
{a}3{/a}/{b}2{/b}*100
I need to substitute in that string those values within the tags with real values from the database, the first example:
SELECT value FROM table WHERE id = 3;
SELECT value FROM table WHERE id = 4;
This function:
preg_replace_callback('/(?>{([^}]+)})(.*)?{\/\1}/sim', 'find_tags_callback', $string);
Actually returns the ids contained in the string, the problem is that I'm stuck there. In pseudo code I would need to:
Extract the first id from the string.
Run my query.
Substitute that id with the correct value.
[Do the same for all tags]
Finish having back the initial string with the correct value inside. The first might be
10*3
the second
40/90*100
Any idea how to do this, I'm completely stuck.
Thanks
Do a database query to get all the values, and put them into an array keyed off the IDs. In the code below, I assume the array is named $tags
.
$new_string = preg_replace_callback('/\{([^}]+)\}(.+?)\{/\1\}/sim',
function ($match) use ($tags) {
return $tags[$match[2]];
}, $string);
The use ($tags)
declaration allows the function to reference the external variable $tags
.