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, replace multiple, and delete characters in strings through clear code examples and output results, and it also mentions additional options such as limiting replacements and case sensitivity.
In PHP, strings are a common data type, and sometimes you need to replace or remove specific characters. PHP provides the convenient str_replace function to accomplish this.
The syntax of str_replace is:
str_replace($search, $replace, $subject);
The function searches the $subject string for $search and replaces each occurrence with $replace .
Example 1: Simple replacement
Code:
$text = "今天是星期一,明天是星期二,后天是星期三。"; $new_text = str_replace("星期一", "周一", $text); echo $new_text;
Output:
今天是周一,明天是星期二,后天是星期三。
Example 2: Replacing multiple characters
Code:
$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.
This example uses an array as the search parameter to replace the words "quick", "brown", and "lazy" with "slow".
Example 3: Deleting specific characters
Code:
$text = "Hello, world!"; $new_text = str_replace("o", "", $text); echo $new_text;
Output:
Hell, wrld!
Here the character "o" is replaced with an empty string, effectively deleting it from the original text.
The str_replace function also supports additional features such as limiting the number of replacements and case‑sensitive searches; refer to the official PHP documentation for more details.
In summary, str_replace is a versatile string‑replacement function that simplifies character substitution and removal tasks, improving code efficiency and readability.
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.