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