PHP Regular expression preg replace
the preg_replace() function is used for regular expression searches and replacements.
Mixed preg_replace(mixed pattern, mixed replacement, mixed subject[, int limit])
|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|
- 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.
- 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.
- 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().
$str = "The quick brown fox jumped over the lazy dog."; $str = preg_replace('/\ s /', '-', $str); echo $str;
The output is:
Example 2, using the array:
$str = "The quick brown fox jumped over the lazy dog."; $patterns = "/quick"; $patterns = "/brown"; $patterns = "/fox"; $replacements = "bear"; $replacements = "black"; $replacements = "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. * /