0
0
PhpHow-ToBeginner · 3 min read

How to Use preg_replace in PHP: Syntax and Examples

Use preg_replace in PHP to search for patterns in a string using regular expressions and replace them with a specified replacement. The function syntax is preg_replace(pattern, replacement, subject), where pattern is a regex, replacement is the new text, and subject is the input string.
📐

Syntax

The preg_replace function has three main parts:

  • pattern: A regular expression enclosed in delimiters (usually slashes /).
  • replacement: The string to replace matches with.
  • subject: The string or array of strings to search and replace in.

It returns the modified string with replacements applied.

php
$result = preg_replace('/pattern/', 'replacement', 'subject string');
💻

Example

This example replaces all digits in a string with the word "number".

php
<?php
$input = "My phone number is 12345.";
$output = preg_replace('/\d+/', 'number', $input);
echo $output;
?>
Output
My phone number is number.
⚠️

Common Pitfalls

Common mistakes when using preg_replace include:

  • Forgetting to use delimiters around the pattern (e.g., /pattern/).
  • Not escaping special regex characters inside the pattern.
  • Using the wrong pattern syntax causing no matches or errors.
  • Expecting preg_replace to modify the original string directly (it returns a new string).
php
<?php
// Wrong: missing delimiters
// $result = preg_replace('pattern', 'replace', 'text'); // This will cause a warning

// Right: with delimiters
$result = preg_replace('/pattern/', 'replace', 'text');
?>
📊

Quick Reference

ParameterDescription
patternRegular expression pattern with delimiters
replacementString to replace matched parts
subjectInput string or array to search
limit (optional)Maximum replacements (default: -1 for unlimited)
count (optional)Variable to store number of replacements done

Key Takeaways

Use delimiters like slashes around your regex pattern in preg_replace.
preg_replace returns a new string; it does not change the original variable.
Escape special regex characters in your pattern to avoid unexpected results.
You can replace multiple matches at once using preg_replace.
Use the optional limit and count parameters to control replacements.