ImpendingDoom ImpendingDoom - 3 months ago 6
PHP Question

How to parse a string using preg_replace_callback

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.


Answer

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
Comments