Current Location: Home> Function Categories> preg_replace

preg_replace

Perform a regular expression search and replacement
Name:preg_replace
Category:Regular processing PCRE
Programming Language:php
One-line Description:Returns a string where the pattern match is replaced by a substring in the given string.

Definition and usage

preg_replace() function returns a string or array of strings where all matches to the pattern or pattern list found in the input are replaced with substrings.

This function is used in three different ways:

  • A pattern and a replacement string. The match of the pattern will be replaced by the replacement string.
  • A pattern array and a replacement string. Any pattern in the matching array will be replaced by the replacement string.
  • An array of pattern and an array of replacement strings. The matches for each pattern will be replaced by strings at the same position in the replace string array. If no item is found at that position in the replacement array, the match will be replaced with an empty string.

The replacement string can contain backward references in the form of \n or n, where n is the index of the group in the pattern. In the returned string, instances of \n and n will be replaced by the substrings that match the group, or, if \0 or $0 is used, they will be replaced by the entire expression.

Note: For each input string, the function evaluates the pattern in the given order. The result of evaluating the first pattern on the string will be used as the input string for the second pattern, and so on. This can lead to unexpected behavior.

Example

Using case-insensitive regular expressions, replace "Microsoft" with "W3School" in the string:

 <?php
$str = 'Visit Microsoft!' ;
$pattern = '/microsoft/i' ;
echo preg_replace ( $pattern , 'W3School' , $str ) ;
?>

Try it yourself

grammar

 preg_replace ( patterns , replacements , input , limit , count )
parameter describe
Patterns Required. Contains regular expressions or regular expression arrays.
replacements Required. Replace strings or replace string arrays.
input Required. A string or array of strings that are replaced on it.
limit

Optional. The default is -1, indicating no limit.

Sets the limit on the number of replacements that can be made in each string.

count Optional. After the function is executed, the variable will contain a number indicating how many replacements have been performed.
Similar Functions
Popular Articles