PHP preg_replace() Function

PHP 正则表达式(PCRE)PHP Regular Expressions (PCRE)

The preg_replace function performs a regular expression search and replace.

Syntax

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

Searches subject for matches to pattern and replaces them with replacement.

Parameter description:

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

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

  • $subject: The target string or array of strings to search and replace.

  • $limit: Optional. The maximum number of replacements for each pattern in each subject string. The default is -1 (unlimited).

  • $count: Optional. The number of replacements performed.

Return Value

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

If matches are found, the replaced subject is returned; otherwise, the unchanged subject is returned. If an error occurs, NULL is returned.

Examples

Replace google with example

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

The execution result is as follows:

example 123,456

Delete whitespace characters

<?php $str = 'runo o b'; $str = preg_replace('/\s+/', '', $str); //Will be changed to 'example' echo $str; ?>

The execution result is as follows:

example

Search and replace using array-based index

<?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.

Using the count parameter

<?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 正则表达式(PCRE)PHP Regular Expressions (PCRE)

Other Extensions