Jordash Jordash - 7 months ago 45
PHP Question

preg_replace round internal value of mapped value

I have a preg_replace firing like this:

echo preg_replace('/(.*?)(?:\()(.*?)(?:\))/', '$1<div class="parenthesis">($2)</div>', $data['display']);

I need to round the variable

I tried this:

echo preg_replace('/(.*?)(?:\()(.*?)(?:\))/', '$1<div class="parenthesis">('.round($2).')</div>', $data['display']);

But it returned a syntax error, i'm not very familiar with preg_replace and am not sure how to get specific in the area I need to round.


You can use preg_replace_callback() for that. It lets you define a callback that gets all matches passed to it. You can then manipulate them as you please before building the new string.

echo preg_replace_callback('/(.*?)(?:\()(.*?)(?:\))/', function($matches) {

    return $matches[0] . '<div class="parenthesis">' . round($matches[1]) . '</div>';

}, $data['display']);