PHP Regular expression preg replace


the preg_replace() function is used for regular expression searches and replacements.

grammar:

Mixed preg_replace(mixed pattern, mixed replacement, mixed subject[, int limit])
Parameters Description
pattern regular expression
replacement Replacement
subject need to match the replaced object
limit Optional, specify the number of replacements, if you omit the limit or its value is -1, then all the matches will be replaced

Supplement

  1. A replacement can contain backslashes of the form \\ n or $n, preferably the latter. Each such reference will be replaced with the text that matches the subpattern within the nth captured parenthesis. N can be from 0 to 99, where \\ 0 or $0 refers to the text that is matched by the entire pattern. Counts the left parenthesis left to right(starting at 1) to get the number of subpatterns.
  2. You can not use the \\ sign to indicate a reverse reference to a substitution pattern after a back reference followed by a number(such as \\ 11). Because it will make preg_replace() confused whether you want a \\ 1 backreference followed by a number 1 or a \\ 11 backreference. The workaround is to use \ 1 1. This results in an isolated $1 backreference, leaving the other 1 simply literal.
  3. The above parameters can be an array in addition to limit. If both pattern and replacement are arrays, they will be processed in the order in which their key names appear in the array, not necessarily in the same numerical order as the index. If an index is used to identify which pattern will be replaced by which replacement, the array should be sorted by the ksort() function before calling preg_replace().

Example 1:

$str = "The quick brown fox jumped over the lazy dog.";
$str = preg_replace('/\ s /', '-', $str);
echo $str;

The output is:

The-quick-brown-fox-jumped-over-the-lazy-dog.

Example 2, using the array:

$str = "The quick brown fox jumped over the lazy dog.";

$patterns[0] = "/quick";
$patterns[1] = "/brown";
$patterns[2] = "/fox";

$replacements[2] = "bear";
$replacements[1] = "black";
$replacements[0] = "slow";

Print preg_replace($patterns, $replacements, $str);
/* Output:
The bear black slow jumped over the lazy dog.
* /
Ksort($replacements);
Print preg_replace($patterns, $replacements, $str);
/* Output:
The slow black bear jumped over the lazy dog.
* /



Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook