Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP preg_replace() Function

PHP preg_replace() Function

PHP Regular Expressions (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:

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

PHP Regular Expressions (PCRE)PHP Regular Expressions (PCRE)