Using PHP str_replace for String Replacement and Deletion
This article explains PHP's str_replace function, detailing its syntax, demonstrating simple replacements, multiple replacements using arrays, and character deletions with code examples, while also noting additional options and linking to further PHP learning resources.
In PHP, strings are a common data type, and sometimes you need to replace or delete certain characters within a string. PHP provides the convenient str_replace function for this purpose.
The syntax of the function is:
str_replace($search, $replace, $subject);This function searches the $subject string for $search and replaces it with $replace .
Below are concrete examples demonstrating the use of str_replace :
Example 1: Simple replacement
$text = "今天是星期一,明天是星期二,后天是星期三。";
$new_text = str_replace("星期一", "周一", $text);
echo $new_text;Result:
今天是周一,明天是星期二,后天是星期三。In this example, "星期一" is replaced with "周一".
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;Result:
The slow fox jumps over the slow dog.Here an array is used to replace the words "quick", "brown", and "lazy" with "slow".
Example 3: Deleting specific characters
$text = "Hello, world!";
$new_text = str_replace("o", "", $text);
echo $new_text;Result:
Hell, wrld!This example removes 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 highly useful string‑replacement function that can conveniently handle character replacement or deletion tasks, improving code efficiency and readability.
Java学习资料领取
C语言学习资料领取
前端学习资料领取
C++学习资料领取
php学习资料领取
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.