Backend Development 5 min read

Using PHP str_replace for String Replacement and Deletion

This article explains the PHP str_replace function, its syntax, and demonstrates simple replacement, multiple replacements, and character deletion through clear code examples, helping developers efficiently manipulate strings in backend applications.

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

In PHP, strings are a very common data type, and sometimes you need to replace or delete certain characters within a string. For this purpose, PHP provides a convenient function str_replace (string replacement) to accomplish the task.

The syntax of the str_replace function is as follows:

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

This function searches the $subject string for $search and replaces it with $replace .

Now let’s look at some concrete examples demonstrating the use of the str_replace function.

Example 1: Simple replacement

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

Output:

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

In this example, the word "星期一" is replaced with "周一" in the original string.

Example 2: Replace 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.

Here an array is used as the search parameter, replacing the words "quick", "brown" and "lazy" with "slow".

Example 3: Delete specified characters

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

Output:

Hell, wrld!

This example removes the character "o" by replacing it with an empty string.

The str_replace function also has other usages, such as specifying the number of replacements, case‑sensitivity, etc. You can consult the PHP official documentation for more details.

In summary, the str_replace function is a very useful string‑replacement tool that can conveniently replace or delete specific characters in a string, improving code efficiency and readability. Hope this article helps you with string replacement operations in PHP.

Java learning material download

C language learning material download

Frontend learning material download

C++ learning material download

PHP learning material download

BackendPHPstringstring-manipulationreplacephp-functionsstr_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.