PHP中如何结合数组与数值字面量使用preg_replace?
Hey there! Let's figure out why that third preg_replace isn't working for you. First, let's start with the most common pitfall when using $0 (or any backreference) in PHP's preg_replace:
The #1 Culprit: PHP Variable Interpolation
If you're using double quotes for your replacement string, PHP will try to parse $0 as a regular variable instead of treating it as a backreference to the full matched text. Since you almost certainly don't have a variable named $0 defined, this will turn your replacement into an empty string (or just the part before $0), making it look like the replacement didn't run at all.
Example of the Mistake:
$test = ['/cat/', '/dog/', '/bird/']; $input = 'A cat, a dog, a bird.'; // These first two work fine $step1 = preg_replace($test[0], 'fluffy cat', $input); $step2 = preg_replace($test[1], 'playful dog', $step1); // BROKEN: Double quotes make $0 get parsed as a PHP variable $step3 = preg_replace($test[2], "cute $0", $step2);
Fixed Versions:
Either use single quotes to prevent variable interpolation:
$step3 = preg_replace($test[2], 'cute $0', $step2);
Or escape the $ with a backslash if you need to use double quotes:
$step3 = preg_replace($test[2], "cute \$0", $step2);
Other Things to Check
If fixing the quotes doesn't solve it, run through these quick checks:
- Does the third regex actually match anything? After the first two replacements, your input string might have changed enough that the third pattern no longer has a match. Test it with
preg_match($test[2], $step2, $matches)— if$matchesis empty, your regex isn't targeting the right content anymore. - Is your third regex valid? Double-check for typos like missing backslashes (e.g.,
/d+/instead of/\d+/) or mismatched delimiters. Invalid regexes will fail silently or return unexpected results.
Give these fixes a try — I bet the quote issue is the root of your problem!
内容的提问来源于stack exchange,提问作者Loïc

