Last updated: November 27, 2026.
When preg_match() reports an unrecognized escape, fix the pattern itself. PHP 8 rejects invalid escapes even without the old uppercase X modifier. If the pattern includes a literal value, quote that value before inserting it into the regex.
<?php
$label = 'part+7/blue';
$pattern = '/' . preg_quote($label, '/') . '/';
foreach (['Stock: part+7/blue', 'Stock: partt7/blue'] as $line) {
$result = preg_match($pattern, $line);
if ($result === false) {
throw new RuntimeException(preg_last_error_msg());
}
echo ($result === 1 ? "Match" : "No match"), PHP_EOL;
}Read the pattern that PHP actually passes to PCRE
Look at the final pattern after PHP has assembled its strings. If a handwritten pattern contains an accidental escape before an ordinary letter, remove that backslash. If it should match a literal backslash, the regex needs an escaped backslash, and the PHP string may require additional escaping. For literal fragments constructed at runtime, preg_quote() takes care of regex metacharacters and the delimiter you pass to it.
Quote the fragment only. Keep deliberate regex operators, anchors and character classes in the trusted surrounding pattern. If all you need is a literal substring check, str_contains() avoids regex syntax entirely.
Distinguish a pattern error from a normal miss
preg_match() returns 1 for a match, 0 for a valid pattern that found no match, and false on failure. A malformed pattern also emits a warning, which often gives more detail than the error string returned by preg_last_error_msg(). Check the warning in development logs and avoid showing it to end users.
The uppercase X and lowercase x modifiers are different. PHP 8 ignores uppercase X. Lowercase x enables extended pattern syntax. When migrating, test both a known matching input and a near miss to catch changes in literal meaning.