Replace and retrieve placeholder value

2019-07-20 09:09发布

Is there any way I can replace one value and retrieve another in the same string in a more efficient way than in the code below, for example a method that combines preg_replace() and preg_match()?

$string = 'abc123';
$variable = '123';
$newString = preg_replace("/(abc)($variable)/",'$1$2xyz', $string);
preg_match("/(abc)($variable)/", $string, $matches);
$number = $matches[2];

1条回答
Root(大扎)
2楼-- · 2019-07-20 10:07

You can use a single call to preg_replace_callback() and update the value of $number in the code of the callback function:

$string = 'abc123';
$variable = '123';

$number = NULL;
$newString = preg_replace_callback(
    "/(abc)($variable)/", 
    function ($matches) use (& $number) {
        $number = $matches[2];
        return $matches[1].$matches[2].'xyz';
    },
    $string
);

I don't think there is a big speed improvement. The only advantage could be on the readability.

查看更多
登录 后发表回答