Backend Development 3 min read

Using PHP str_replace for String Replacement and Deletion

This article explains PHP's str_replace function, its syntax, and provides three practical examples showing simple replacement, multiple replacements with arrays, and character deletion, while also noting additional options available in the official documentation.

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

In PHP, strings are common data types and sometimes you need to replace or delete certain characters; the built-in str_replace function provides a simple way to accomplish this.

The syntax is str_replace($search, $replace, $subject); where the function searches the $subject string for $search and replaces it with $replace .

Example 1 demonstrates a basic replacement, converting "星期一" to "周一" in a Chinese sentence.

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

The output is "今天是周一,明天是星期二,后天是星期三。"

Example 2 shows replacing multiple words using an array, changing "quick", "brown", and "lazy" to "slow" in an English sentence.

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

The result is "The slow fox jumps over the slow dog."

Example 3 illustrates deleting characters by replacing "o" with an empty string.

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

The output is "Hell, wrld!"

Additional options such as limiting replacement count or case sensitivity are available in the official PHP documentation.

In summary, str_replace is a versatile function for string manipulation, enabling efficient replacement or removal of characters and improving code readability.

PHPtutorialstring 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.