Using PHP str_replace for String Replacement and Deletion
This article explains PHP's str_replace function, showing its syntax and demonstrating how to replace single words, multiple words, or delete characters in strings through clear code examples and their outputs, helping developers efficiently manipulate text in backend applications.
In PHP, strings are a common data type, and the str_replace function provides a simple way to replace or remove characters within a string.
The syntax of str_replace is: str_replace($search, $replace, $subject); The function searches the $subject string for the value(s) specified by $search and replaces them with $replace.
Example 1: Simple replacement
$text = "今天是星期一,明天是星期二,后天是星期三。";<br/>$new_text = str_replace("星期一", "周一", $text);<br/>echo $new_text;Output: 今天是周一,明天是星期二,后天是星期三。 Example 2: Replacing multiple characters
$text = "The quick brown fox jumps over the lazy dog.";<br/>$new_text = str_replace(array("quick", "brown", "lazy"), "slow", $text);<br/>echo $new_text;Output: The slow fox jumps over the slow dog. In this example, an array is used to replace the words "quick", "brown", and "lazy" with "slow".
Example 3: Deleting specific characters
$text = "Hello, world!";<br/>$new_text = str_replace("o", "", $text);<br/>echo $new_text;Output: Hell, wrld! This demonstrates removing the character "o" by replacing it with an empty string.
The str_replace function also supports additional options such as limiting the number of replacements and case‑sensitive matching; refer to the official PHP documentation for more details.
In summary, str_replace is a versatile string‑replacement function that can efficiently handle both substitution and deletion tasks, improving code readability and performance in PHP backend development.
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.
