Understanding PHP preg_replace: Syntax, Parameters, and Practical Examples
This article explains PHP's preg_replace function, detailing its signature, parameter meanings, return values, and providing multiple code examples that demonstrate pattern matching, backreferences, array handling, and replacement limits for effective string manipulation in backend development.
preg_replace() executes a regular expression search and replace in PHP.
It searches the $subject for matches to $pattern and replaces them with $replacement. Optional parameters $limit and &$count control the maximum replacements and capture the number of replacements performed.
Parameters pattern: the regex pattern or an array of patterns; PCRE modifiers (including the deprecated e) may be used. replacement: the replacement string or array; can contain back‑references such as \$1 or \\1, with special handling for adjacent digits (e.g., ${1}1). subject: the string or array to be processed; if an array, the function returns an array of results. limit: maximum number of replacements per pattern (default -1 for unlimited). count: variable passed by reference that receives the total number of replacements.
Return value : the modified string, or an array when subject is an array; NULL is returned on error.
Example 1
<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>Output: April1,2003 Example 2
<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>Output: The bear black slow jumped over the lazy dog. Example 3
<?php
$patterns = array('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/', '/^\s*{(\w+)}\s*=/');
$replace = array('\3/\4/\1\2', '\$1 =');
echo preg_replace($patterns, $replace, '{startDate} = 1999-5-27');
?>Output: $startDate=5/27/1999 Example 4
<?php
$str = 'foo o';
$str = preg_replace('/\s\s+/', ' ', $str);
// Resulting string is 'foo o'
echo $str;
?>Output: foo o Example 5
<?php
$count = 0;
echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', $count);
echo $count; // 3
?>Output: *** to and the replacement count 3.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
