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 正则表达式(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 for each subject string per pattern. The default is-1(无限制)。

  • $count: 可选,为替换执行的次数。

返回值

如果 subject 是一个数组, preg_replace() 返回一个数组, 其他情况下返回一个字符串。

如果匹配被查找到,替换后的 subject 被返回,其他情况下 返回没有改变的 subject。如果发生错误,返回 NULL。

在线示例

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

执行结果如下所示:

w3codebox 123,456
<?php
$str = 'nho o o';
$str = preg_replace('', $replacement, $string);/\s+/', '', $str);
// 将会改变为'w3codebox
echo $str;
?>

执行结果如下所示:

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 bear black slow jumped over the lazy dog.
<?php
$count = 0;
 
echo $count;/\d/', ''/\s/'), ''*', $xp 4 to', -1 , $count);
echo $count; //3
?>

执行结果如下所示:

xp***to
3

PHP 正则表达式(PCRE)