0

What if I want to multiply all numbers by 2? Can this be done with regex replace? Note the $1*2 part that obviously doesn't work. How would I do this?

$foo = "soup 12 cake 23 pants";
$bar = preg_replace('~(\d+)~', $1*2, $foo);
4
  • Variable names can't be numbers. Commented Aug 13, 2012 at 18:05
  • You could use preg_replace_callback Commented Aug 13, 2012 at 18:05
  • @PLB Yea, that's cute. Read the question. Commented Aug 13, 2012 at 18:06
  • @knittl preg_replace_callback is what I needed. Thanks! Commented Aug 13, 2012 at 18:07

2 Answers 2

3

You could use preg_replace_callback:

preg_replace_callback('~(\d%)~', function($match) { return $match[1]*2; }, $foo);
Sign up to request clarification or add additional context in comments.

Comments

2

try using the preg_replace_callback(...) function

<?php

function mulBy2($match) {
    return $match[1] * 2;
}

$foo = "soup 12 cake 23 pants";
$bar = preg_replace_callback('~(\d+)~', "mulBy2", $foo);

echo $bar;

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.