PHP preg_replace() Function
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, which 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 be searched and replaced.
-
$limit: optional, the maximum number of replacements for each pattern on each subject string. Default is -1 (no limit).
-
$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 a match is found, the replaced subject is returned; otherwise the unchanged subject is returned. If an error occurs, NULL is returned.
Example
Replace google with runoob
The execution result is as follows:
runoob 123,456
Remove whitespace characters
The execution result is as follows:
runoob
Use array-index-based search and replace
The execution result is as follows:
The bear black slow jumped over the lazy dog.
Using the count parameter
The execution result is as follows:
xp***to
3