preg_replace usage
PHP regular expression search replace usage
$replaced_content = preg_replace($pattern, $replacement, $content [, int $limit = -1 [, int &$count]])
Notes on preg_replace behavior
- The regex pattern must be delimited by a valid delimiter. e.g.
/abc/
,#abc#
, etc. - The modifier flag “i” after / is specified to ignore case while matching. You can combine multiple flags. For a full list if flags you can visit PHP: possible modifiers in regex patterns – manual.
- Php preg_replace follows PCRE – Perl compatible regular expressionss.
- Official document for preg_replace can be viewed at PHP: preg_replace manual.
- Also visit: Regular expression – Wikipedia.
More preg_replace examples for beginners
Here are few preg_replace regex examples (level: beginner) for some common scenarios.
-
PHP preg_replace – optional one character regex example
Here the regular expression (regex) pattern contains question mark (“?”) and the char precedded by “?” is matched optionally in the content. Also note that the engine uses greedy match. That means it matches the optional char whenever possible. Here is PHP preg_replace example for optional one char match link.
-
PHP preg_replace – optional character group regex example
Here the regular expression (regex) pattern contains optional character group enclosed within parentheses and followed by questiom mark (“?”). The regex engine tries to match the either the whole group or nothing. Also note that the engine uses greedy match. Here is PHP preg_replace example for optional char group match link.
-
PHP preg_replace – back reference within pattern example
Here the match is grouped using parentheses and that group is accessed using backslash followed by the number of group. For first group the number is 1. Also note that we changed the regex delimiter from slash (/) to hash (#) to make pattern more readable as slash is part of regex. Here is PHP preg_replace example for back reference within pattern link.
-
PHP preg_replace – dot all (PCRE_DOTALL) example
By default dot does not match newline char. When we specify dot all (using “s” regex modifier flag) it matches with newline also. These is useful for multiline content matching. Here is PHP preg_replace example for dot all (PCRE_DOTALL) match link.