Using PHP preg_replace() for String Replacement: Syntax, Examples, and Tips
This article explains the PHP preg_replace() function, its basic syntax, and provides multiple code examples showing how to replace specific characters, optional characters, digits, perform case‑insensitive replacements, and mask email addresses using regular expressions.
In PHP, the preg_replace() function is a powerful and flexible tool that allows searching and replacing strings using regular expressions, enabling tasks such as removing specific characters or substituting patterned text.
Basic Syntax of preg_replace()
preg_replace(pattern, replacement, subject);The pattern is the regular expression to match, replacement is the string to replace matches with, and subject is the target string on which the operation is performed.
Below are concrete examples demonstrating how to use preg_replace() for various replacement scenarios.
Replacing Specific Characters in a String
Given a string containing the character “#”, the following code replaces all “#" with “_”.
$str = "Hello#World#";
$newStr = preg_replace('/#/', '_', $str);
echo $newStr; // Output: Hello_World_Replacing Multiple Optional Characters
This example replaces any occurrence of “a”, “b”, or “c” with “x”.
$str = "abcde";
$newStr = preg_replace('/[abc]/', 'x', $str);
echo $newStr; // Output: xxxdeReplacing Digits in a String
To replace all digits with “*”, the \d token is used.
$str = "abc123def456";
$newStr = preg_replace('/\d/', '*', $str);
echo $newStr; // Output: abc***def***Case‑Insensitive Replacement
Adding the /i modifier makes the pattern case‑insensitive.
$str = "Hello World";
$newStr = preg_replace('/world/i', 'PHP', $str);
echo $newStr; // Output: Hello PHPReplacing Email Addresses
This example masks email addresses using a regular expression that matches typical email patterns.
$str = "My email is [email protected]";
$newStr = preg_replace('/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/', '***', $str);
echo $newStr; // Output: My email is ***These examples illustrate basic uses of preg_replace(); the function also offers many additional options and features for advanced string manipulation.
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.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
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.
