Backend Development 3 min read

Using PHP's str_replace Function for String Replacement and Deletion

This article explains how PHP's str_replace function works, shows its syntax, and provides three practical examples—simple replacement, multiple replacements using an array, and character deletion—demonstrating how to manipulate strings efficiently in backend development.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's str_replace Function for String Replacement and Deletion

In PHP, strings are a fundamental data type, and developers often need to replace or remove specific characters within them; PHP offers the convenient str_replace function to accomplish these tasks.

The function signature is:

str_replace($search, $replace, $subject);

It searches the $subject string for occurrences of $search and replaces them with $replace .

Example 1: Simple replacement

$text = "今天是星期一,明天是星期二,后天是星期三。";
$new_text = str_replace("星期一", "周一", $text);
echo $new_text;

Output:

今天是周一,明天是星期二,后天是星期三。

Example 2: Replacing multiple characters

$text = "The quick brown fox jumps over the lazy dog.";
$new_text = str_replace(array("quick", "brown", "lazy"), "slow", $text);
echo $new_text;

Output:

The slow fox jumps over the slow dog.

Example 3: Deleting specific characters

$text = "Hello, world!";
$new_text = str_replace("o", "", $text);
echo $new_text;

Output:

Hell, wrld!

The str_replace function also supports additional options such as limiting the number of replacements and case‑sensitive matching; further details can be found in the official PHP documentation.

In summary, str_replace is a versatile and easy‑to‑use tool for performing string replacements or deletions, helping developers write cleaner and more efficient code.

backendPHPTutorialstring replacementstr_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.