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, multiple replacements using an array, and character deletion—showing how to efficiently manipulate strings in backend development.
In PHP, strings are a common data type and the built‑in str_replace function provides a simple way to replace or delete characters within a string.
The syntax is str_replace($search, $replace, $subject); where the function searches the $subject for $search and replaces each occurrence with $replace .
Example 1 – Simple replacement
$text = "今天是星期一,明天是星期二,后天是星期三。";
$new_text = str_replace("星期一", "周一", $text);
echo $new_text;Output: 今天是周一,明天是星期二,后天是星期三。
Example 2 – Replacing multiple substrings
$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 characters
$text = "Hello, world!";
$new_text = str_replace("o", "", $text);
echo $new_text;Output: Hell, wrld!
The function also supports optional parameters such as limiting the number of replacements or performing case‑sensitive searches, which are documented in the official PHP manual.
In summary, str_replace is a versatile and efficient tool for string manipulation in PHP, allowing developers to replace or remove specific characters or substrings with minimal code.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.