I want to parse a string that looks something like this:
((24x_12_)+(_42_+24))/2
using preg_replace_callback():
preg_replace_callback(
// some regex to match anything that starts with '_' and ends with '_',
function($matches) {
// some operation
},
'((24x_12_)+(_42_+24))/2'
)
so anything that starts and ends with _
is replaced, in the above example above it would be _12_
and _42_
more info:
/_(.+)_/
_12_
is the identifier.答案 0 :(得分:1)
Give this a try:
echo preg_replace_callback(
'|_(.*?)_|',
function($match) {
$number = $match[1];
return "[There used to be a $number here.]";
},
'((24x_12_)+(_42_+24))/2'
); # ((24x[There used to be a 12 here.])+([There used to be a 42 here.]+24))/2
答案 1 :(得分:1)
preg_replace_callback()
would work fine to replace _12_
with the value with ID 12
from your database, and maybe even perform 2-operand arithmetic. However it's entirely unsuitable for calculating the end result of the complex expression represented by that string. I mean, you could bruteforce your way through it if you're truly determined, but there are much better methods.
What you should do is implement an expression parser that will turn your string into a series of tokens that can then be interpreted by something to perform the actual calculation, eg: the Shunting-Yard Algorithm.