How to parse a string using preg_replace_callback

时间:2016-08-31 17:05:47

标签: php regex

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:

  1. I need the right regex: something like /_(.+)_/
  2. The outcome would be a mathematical expression except the replaced values are calculated based on values from the DB, so _12_ is the identifier.

2 个答案:

答案 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.