English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP preg_replace() Function Usage and Example

PHP Regular Expression (PCRE)

The preg_replace function performs a search and replace operation using a regular expression.

Syntax

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ])

Search for the part of subject that matches pattern and replace it with replacement.

Parameter Description:

  • $pattern: The pattern to be searched, which can be a string or an array of strings.

  • $replacement: The string or array of strings to be used for replacement.

  • $subject: The target string or array of strings to be searched and replaced.

  • $limit: Optional, the maximum number of replacements allowed for each subject string per pattern. The default is-1(Unlimited).

  • $count: Optional, indicates the number of replacements performed.

Return value

If the subject is an array, preg_replace() returns an array; otherwise, it returns a string.

If a match is found, the subject after replacement is returned. Otherwise, the original subject is returned. If an error occurs, NULL is returned.

Online example

<?php
$string = 'google'; 123, 456';
$pattern = '';/(\w+) (\d+), (\d+)/i';
$replacement = 'w3codebox ${2},$3';
echo preg_replace($pattern, $replacement, $string);
?>

The execution result is as follows:

w3codebox 123,456
<?php
$str = 'nho o o';
$str = preg_replace('/\s+/', '', $str);
// will be changed to 'w3codebox
echo $str;
?>

The execution result is as follows:

w3codebox
<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '';/quick/';
$patterns[1] = '';/brown/';
$patterns[2] = '';/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>

The execution result is as follows:

The bear black slow jumped over the lazy dog.
<?php
$count = 0;
 
echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count);
echo $count; //3
?>

The execution result is as follows:

xp***to
3

PHP Regular Expression (PCRE)