PHP preg_replace – test regex online

Input
Pattern example: /abc/i
Replacement
Content

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

  1. The regex pattern must be delimited by a valid delimiter. e.g. /abc/, #abc#, etc.
  2. 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.
  3. Php preg_replace follows PCRE – Perl compatible regular expressionss.
  4. Official document for preg_replace can be viewed at PHP: preg_replace manual.
  5. Also visit: Regular expression – Wikipedia.

More preg_replace examples for beginners

Here are few preg_replace regex examples (level: beginner) for some common scenarios.

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

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

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

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

Comments

Click here to write/view comments