Advertisement
Intermediate PHP, Regular Expressions in PHP

How does preg_replace let you find and replace text matching a regular expression pattern, and how do capture groups let you reuse parts of the matched text in the replacement?

Short answer

The preg_replace function searches a string for text matching a given pattern and replaces every match with a specified replacement string, and by wrapping specific parts of your pattern in parentheses to create capture groups, you can reference those exact matched portions…

Save PHP mock interview
Advertisement
AModel answer
The preg_replace function searches a string for text matching a given pattern and replaces every match with a specified replacement string, and by wrapping specific parts of your pattern in parentheses to create capture groups, you can reference those exact matched portions within the replacement string using a dollar sign followed by the group's number, letting you rearrange or reuse specific pieces of the matched text rather than only ever replacing it entirely.
$formatted = preg_replace('/(\d{3})(\d{3})(\d{4})/', '($1) $2-$3', '5551234567');
echo $formatted;
Real-world example
A phone number formatting function uses capture groups within a regular expression to rearrange a plain string of ten digits into a nicely formatted phone number with parentheses and a dash, reusing the originally captured digit groups in a new arrangement.
Likely follow-ups
  • What is the difference between preg_replace and preg_replace_callback?
  • How do you reference a named capture group instead of a numbered one in the replacement string?
Related topics