Mastering PHP's preg_replace: Syntax, Parameters, and Real-World Examples
This article explains PHP's preg_replace function, detailing its purpose, parameter list, return values, and provides three practical code examples that illustrate pattern matching, multiple replacements, and usage of limit and count options.
Function Overview
preg_replace() performs a regular‑expression search and replace on a string or an array of strings.
How It Works
The function scans the $subject for matches to $pattern and substitutes each match with $replacement. If $subject is an array, the operation is applied to every element and an array is returned.
Parameter Details
pattern – The regex pattern to search for. It can be a string or an array of strings. PCRE modifiers, including the deprecated e, may be used.
replacement – The replacement string or array. When pattern is an array and replacement is a single string, that string is used for all patterns. If both are arrays, each pattern is paired with the corresponding replacement element; missing replacements are treated as empty strings.
subject – The input string or array of strings.
limit – Maximum number of replacements per pattern per subject. Default is -1 (no limit).
count – Optional variable that will be filled with the total number of replacements performed.
Return Value
If $subject is an array, an array of results is returned; otherwise a string is returned. If no matches are found, the original subject is returned unchanged. On error, NULL is returned.
Example 1 – Reformatting a Date
<?php
$string = 'April 15, 2020';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>Output:
April1,2020Example 2 – Multiple Patterns and Replacements
<?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 – Using Count and Limit
<?php
$count = 0;
echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1, $count);
echo $count; // 3
?>Output:
xp***to
3Signed-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.
