In PHP, preg_replace() replaces every match of a regular expression with a replacement string (or each pattern in an array).
It works on a string or an array of strings. Unlike preg_filter(), non-matching subjects are kept unchanged. You can limit how many replacements happen and receive the count by reference.
Syntax
Call preg_replace() with the values you need. Start with this line.
PHP
$new = preg_replace('/\s+/', ' ', $text);
Call
What it does
preg_replace('/\d+/', '#', 'a1b22c')
Returns "a#b#c".
preg_replace('/cat/', 'dog', 'a cat')
Returns "a dog".
preg_replace('/\d+/', 'X', 'hello')
Returns "hello" unchanged when nothing matches.
In the replacement, $0 is the full match and $1, $2 are capturing groups. For per-match PHP logic, use preg_replace_callback() instead.
Library declarations
PHP
preg_replace(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int &$count = null): string|array|null
Parameters
Parameter
Description
pattern
Required. A pattern string with delimiters, or an array of patterns.
replacement
Required. Replacement string or array of strings. May include $n backreferences.
subject
Required. String or array of strings to rewrite.
limit
Optional. Max replacements per subject. Default -1 means replace all.
count
Optional. Receives the number of replacements performed.
Return Value
Return Value
Description
string|array|null
The subject after replacements. For arrays, every element is returned (changed or not). null on error.
PHP Examples
Example 1 — Replace Digits with a Marker
Swap every run of digits for a single # character.
42 is left alone because it is not matched by [a-z]+.
Frequently Asked Questions
It searches a string (or array of strings) for a regular expression and replaces each match with the given replacement.
Both replace matches. preg_replace() always returns every subject. preg_filter() returns only subjects that matched (or null for a non-matching string).
Use preg_replace_callback() or preg_replace_callback_array(). Those pass each match to your callable.
It caps how many replacements happen for each subject. -1 means no limit.
Only after careful escaping with preg_quote() for literal parts. Prefer fixed patterns. Untrusted patterns risk errors and ReDoS.