MongooseWhere programmers kick back and build silly things together.

All help topics · Link to this topic

Showing help on 'pcre_replace()'

Syntax: pcre_replace (STR <subject>, STR <pattern>) => STR

The function `pcre_replace()' replaces <subject> with replacements found in <pattern> using PCRE2 regular expressions.

The pattern string has a specific format that must be followed, which should be familiar if you have used the likes of Vim, Perl, or sed. The string is composed of four elements, each separated by a delimiter (typically a slash (/) or an exclamation mark (!)), that tell the regular expression engine how to parse your replacement. We'll break the string down and mention relevant options below:

  1. Type of search to perform. In MOO, only 's' is valid. This parameter is kept for the sake of consistency.
  2. The regular expression pattern to match.
  3. The replacement text to substitute for each match.
  4. Optional modifiers:
g: Global. This will replace all occurrences in your string rather than stopping at the first.
i: Case-insensitive. Uppercase, lowercase, it doesn't matter. All will be replaced.

The replacement text can use placeholders in the form of a dollar sign and a number corresponding to a capture group (e.g. $1 will be replaced with the text from the first capture group, $2 the second, etc).

Examples:

Replace one word with another:
pcre_replace("I like banana pie. Do you like banana pie?", "s/banana/apple/g")
=> "I like apple pie. Do you like apple pie?"

Replace text from a capture group:
;pcre_replace("You can find it in objref #1234.", "s/objref (#\d*)/object $1/g")
=> "You can find it in object #1234."

If you find yourself wanting to replace a string that contains slashes, it can be useful to change your delimiter to an exclamation mark:
pcre_replace("Unix, wow! /bin/bash is a thing.", "s!/bin/bash!/bin/fish!g")
=> "Unix, wow! /bin/fish is a thing."