有没有什么方法可以替换一个值并以比下面的代码更有效的方式在同一个字符串中检索另一个值,例如一个结合preg_replace()
和preg_match()
的方法?
$string = 'abc123';
$variable = '123';
$newString = preg_replace("/(abc)($variable)/",'$1$2xyz', $string);
preg_match("/(abc)($variable)/", $string, $matches);
$number = $matches[2];
答案 0 :(得分:0)
您可以使用preg_replace_callback()
的单个调用,并在回调函数的代码中更新$number
的值:
$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
);
我认为速度没有太大提升。唯一的优势可能在于可读性。