Backend Development 4 min read

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.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP preg_replace() for String Replacement: Syntax, Examples, and Tips

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()

<code>preg_replace(pattern, replacement, subject);</code>

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 “_”.

<code>$str = "Hello#World#";
$newStr = preg_replace('/#/', '_', $str);
echo $newStr; // Output: Hello_World_</code>

Replacing Multiple Optional Characters

This example replaces any occurrence of “a”, “b”, or “c” with “x”.

<code>$str = "abcde";
$newStr = preg_replace('/[abc]/', 'x', $str);
echo $newStr; // Output: xxxde</code>

Replacing Digits in a String

To replace all digits with “*”, the \d token is used.

<code>$str = "abc123def456";
$newStr = preg_replace('/\d/', '*', $str);
echo $newStr; // Output: abc***def***</code>

Case‑Insensitive Replacement

Adding the /i modifier makes the pattern case‑insensitive.

<code>$str = "Hello World";
$newStr = preg_replace('/world/i', 'PHP', $str);
echo $newStr; // Output: Hello PHP</code>

Replacing Email Addresses

This example masks email addresses using a regular expression that matches typical email patterns.

<code>$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 ***</code>

These examples illustrate basic uses of preg_replace() ; the function also offers many additional options and features for advanced string manipulation.

backendPHPTutorialregexstring replacementpreg_replace
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.