Master PHP’s str_replace: Simple Replacements, Bulk Swaps, and Deletions
This guide explains PHP's str_replace function, covering its syntax, basic single replacements, array‑based multiple replacements, character deletions, and additional options, with clear code examples and expected outputs to help developers manipulate strings efficiently.
In PHP, strings are common data types, and the built‑in str_replace function provides a straightforward way to replace or remove characters within a string.
Function Syntax
str_replace($search, $replace, $subject);The function searches the $subject string 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 Words
$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! Beyond these basic usages, str_replace also supports limiting the number of replacements and case‑sensitive operations; further details are available in the official PHP documentation.
Overall, mastering str_replace enables efficient string manipulation, improving code readability and performance in PHP applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
