PHP preg_replace() function

The preg_replace() function is a built-in function of PHP. It is used to perform a regular expression search and replace.

This function searches for pattern in subject parameter and replaces them with the replacement.

Syntax

Parameters

This function accepts five parameters, which are described below:

pattern

This parameter can be either a string or an array with strings. It holds the pattern to search in subject parameter.

replacement

It is a string or an array with strings parameter. This parameter replaces the pattern matched in subject parameter. It is a mandatory parameter.

  • If the replacement parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string.
  • If both replacement and pattern parameters are arrays, each pattern will be replaced by the replacement counterpart.
  • If the replacement array consists of fewer elements than the pattern array, any extra pattern will be replaced by an empty string.

subject

The subject parameter can also be either a string or an array of string to search and replace.

If the subject is an array, the search and replacement are performed on every entry of subject, and the returned value will also be an array.

limit

The limit is an optional parameter that specifies the maximum possible replacement for each pattern. The default value of limit is -1, which means no limit.

count

It is an optional parameter. If this parameter is passed, this variable will contain the number of replacements done. This parameter added in PHP 5.1.0.

Return Type

The preg_replace() function returns an array if the subject parameter is an array otherwise it returns a string.

  • After the replacement has done, the modified string will be returned.
  • If any matches do not find, the string will remain unchanged.

Examples

Simple Replacing

See the detailed examples to understand the preg_replace() function practically:

Example using backreference followed by numeric literals

Output:

May 5, 2020 

Example to strip whitespace

In the below example, preg_replace() removes all extra whitespace from the given string.

Output:

Camila Cabello is a Hollywood singer. 

Example using indexed arrays

This example will contain a pattern array to replace with replacement array.

Output:

String after replacement: The fox brown quick runs away from the zoo.

In the above example, we can see that output is not same as we want. Therefore, by applying ksort() on patterns and replacements before using preg_replace(), we can get what we want to.

Output:

String after replacement using ksort: The quick brown fox runs away from the zoo.

Next TopicPHP Functions




Contact US

Email:[email protected]

preg_replace() function
10/30