Master PHP’s str_replace: Replace, Remove, and Transform Strings Easily
This guide explains how to use PHP's str_replace function to search for, replace, or delete characters in strings, providing clear syntax, multiple practical examples, and tips for advanced usage such as handling arrays and limiting replacements.
In PHP, strings are common, and sometimes you need to replace or delete characters. PHP provides the convenient function str_replace for this purpose.
Function Syntax
str_replace($search, $replace, $subject);The function searches for $search in $subject and replaces it with $replace.
Examples
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 str_replace function also supports additional options such as limiting the number of replacements and case‑sensitivity control; refer to the official PHP documentation for more details.
In summary, str_replace is a versatile string‑replacement function that simplifies modifying strings, improving code efficiency and readability.
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.
