preg_replace warns about a bad delimiter and returns null
Warning: preg_replace(): Delimiter must not be alphanumeric, backslash, or NUL byteShort answer
Every PCRE pattern in PHP must start and end with the same delimiter character, such as /, # or ~. The warning means the first character is a letter, digit, backslash or space, the closing delimiter is missing, or the delimiter appears unescaped inside the pattern. Wrap the pattern, pick a delimiter that is not in it, and run user input through preg_quote.
Fix it fast
1Find out which cause you have
Print the exact pattern string and its first and last character. The warning is about those two characters, so look at them before anything else.
<?php $pattern = 'hello'; // paste the pattern you pass in var_dump($pattern, $pattern[0], substr($pattern, -1));2Match what you see, then jump to its fix
- 1
Delimiter must not be alphanumeric, backslash, or NUL byteThe pattern has no delimiters at allFix - 2
No ending delimiter '/' found, or Unknown modifier followed by a character from your patternThe closing delimiter is missing, or the delimiter also appears inside the patternFix - 3
The warning appears only for some inputs, and the pattern is built with string concatenationText built from user input contains the delimiterFix - 4
No ending matching delimiter '}' found, or Unknown modifier ']'Bracket delimiters meet an unescaped bracket in the patternFix
- 1
What does the error look like?
Warning: preg_replace(): Delimiter must not be alphanumeric, backslash, or NUL byteWarning: preg_replace(): No ending delimiter '/' foundWarning: preg_replace(): No ending matching delimiter '}' foundWarning: preg_replace(): Unknown modifier ']'
Cause 1 of 4
The pattern has no delimiters at all
1Check
The first character of the pattern is a letter, digit or backslash, for example 'hello' or '\d+'. PHP reads that first character as the delimiter and rejects it.
<?php
var_dump(preg_match('hello', 'hello world')); // warning, returns false2Fix
Put the same non-alphanumeric character before and after the pattern. Flags go after the closing delimiter.
<?php
$out = preg_replace('/hello/i', 'bye', 'Hello world');
echo $out; // bye world3Verify
The call returns a string, not null, and no warning is printed.
<?php
var_dump(preg_replace('/hello/i', 'bye', 'Hello world'));Confirmed by php.net
Cause 2 of 4
The closing delimiter is missing, or the delimiter also appears inside the pattern
1Check
Look for the delimiter character inside the pattern. A URL with / in a /-delimited pattern ends the pattern early, and whatever follows is read as modifiers.
<?php
var_dump(preg_match('/http://example.com/', 'http://example.com/')); // warning2Fix
Escape the delimiter with a backslash, or choose another delimiter that does not occur in the pattern.
<?php
preg_match('/http:\/\/example\.com/', $text);
preg_match('#http://example\.com#', $text); // same pattern, no escaping needed3Verify
Both calls return 1 for a matching string instead of false.
<?php
var_dump(preg_match('#http://example\.com#', 'http://example.com'));Confirmed by php.net
Cause 3 of 4
Text built from user input contains the delimiter
1Check
Find the place where a variable is joined into the pattern. Any / or other special character in that value changes the pattern.
grep -rn "preg_" src/2Fix
Pass the value through preg_quote and give it the delimiter as the second argument, so the delimiter is escaped too.
<?php
$word = $_GET['q'] ?? '';
$pattern = '/' . preg_quote($word, '/') . '/i';
$out = preg_replace($pattern, '<b>$0</b>', $text);3Verify
Search for a value containing a slash and an asterisk, such as a/b*, and confirm no warning appears.
<?php
$w = 'a/b*';
var_dump(preg_replace('/' . preg_quote($w, '/') . '/', 'X', 'a/b* c'));Confirmed by php.net
Cause 4 of 4
Bracket delimiters meet an unescaped bracket in the pattern
1Check
A pattern wrapped in {} or [] or () or <> treats a literal bracket of the same kind as a nesting character. A literal bracket must be escaped.
<?php
var_dump(preg_match('{[}]}', 'x')); // Unknown modifier ']'2Fix
Escape the literal bracket, or switch to a delimiter such as / or # that you do not need inside the pattern.
<?php
preg_match('{[\}]}', '}');
preg_match('#[}]#', '}');3Verify
Both calls return 1 with no warning.
<?php
var_dump(preg_match('#[}]#', '}'));Confirmed by php.net
How do I stop it coming back?
- Use # or ~ as the delimiter for patterns that contain slashes, such as URLs and file paths.
- Always wrap interpolated values in preg_quote($value, '/') with the delimiter you chose.
- Check preg_replace results with === null, because PHP returns null when the pattern fails.
- Keep long patterns in a named constant so the delimiters are written once.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack end
Apache returns 403 when a URL contains %3F
a request like /page%3Fname=test is refused while /page?name=test works
Recent Apache httpd blocks a rewrite when the request contains an encoded question mark (%3F) and the rewritten target has a literal ?.
2 causes, each with a fixBack end
Apache returns 500 with Premature end of script headers
500 Internal Server Error
Apache ran your script, but the script printed no valid HTTP header before its output.
3 causes, each with a fixBack end
Apache returns 503 or 504 because PHP-FPM did not answer in time
Error dispatching request
Apache sent the request to PHP-FPM and gave up waiting.
3 causes, each with a fixBack end
AWS SDK for PHP cannot get credentials from the instance profile metadata server
Error retrieving credentials from the instance profile metadata server.
The SDK tries the EC2 instance metadata service when it has no valid credentials from anywhere earlier in its chain.
4 causes, each with a fixBack end
AWS SDK for PHP rejects requests: the signature is from the future
Signature not yet current: {date} is still later than {date}
AWS compares the timestamp in your signed request with its own clock.
2 causes, each with a fix