Using PHP str_replace for String Replacement and Deletion

This article explains the PHP str_replace function, its syntax, and demonstrates three practical examples—simple replacement, replacing multiple words with an array, and deleting characters—showing the resulting output and highlighting 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 a common data type, and developers often need to replace or remove specific characters; the built‑in str_replace function provides a simple way to accomplish this.

The function syntax is: str_replace($search, $replace, $subject); It searches the $subject string for the $search value and replaces each occurrence 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 function also supports additional options such as limiting the number of replacements or performing case‑sensitive searches; refer to the PHP official documentation for more details.

In summary, str_replace is a versatile string‑replacement tool that simplifies character substitution and removal, improving code efficiency and readability for PHP developers.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPTutorialphp-functionsstring-manipulationstr_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

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.