用分割值替换字符串中的数字?

时间:2014-06-09 07:41:06

标签: php

有没有办法在PHP(可能使用正则表达式或preg_replace)中查找字符串中的每个数字,然后将其除以2?让我们说字符串是这样的:

John has 20 apples and Maria has 100 pears.

然后将其转换为

John has 10 apples and Maria has 50 pears.

我不确定如何在preg_replace中传递替换的变量,这就是我所做的,但任何php头脑都可以看到这不起作用:

$output = preg_replace("([0-9]+)", "\$1"/2, $string);

1 个答案:

答案 0 :(得分:2)

使用preg_replace_callback()试用此代码。这将为您提供预期的结果。

<?php
$string = "John has 20 apples and Maria has 100 pears.";
$output = preg_replace_callback(
        "([0-9]+)",
        function ($matches) {
            return ($matches[0]/2);
        },
        $string
    );
echo "Result : ".$output;
?>

<强>输出

Result : John has 10 apples and Maria has 50 pears.