Using str_replace() in PHP: Syntax, Parameters, and Examples
This article explains the PHP str_replace() function, covering its syntax, parameter details, return value, and provides three practical code examples—including single, multiple, and case‑insensitive replacements—to help developers master string manipulation in backend development.
In PHP, string manipulation is a common task, and the str_replace() function is widely used to replace specific characters or substrings.
The syntax of str_replace() is:
str_replace(search, replace, subject)Parameter description:
search : the value to be replaced; can be a string or an array.
replace : the replacement value; can be a string or an array (must match the size of search when both are arrays).
subject : the target string on which the replacement is performed.
Return value:
The function returns the string after replacement.
Example 1: Replace a single character
$str = "Hello, World!";
$newStr = str_replace("World", "PHP", $str);
echo $newStr; // Output: Hello, PHP!This example replaces "World" with "PHP" and prints the result.
Example 2: Replace multiple characters
$str = "Hello, World!";
$search = array("Hello", "World");
$replace = array("Hi", "PHP");
$newStr = str_replace($search, $replace, $str);
echo $newStr; // Output: Hi, PHP!This example replaces "Hello" with "Hi" and "World" with "PHP".
Example 3: Case‑insensitive replacement
$str = "Hello, world!";
$newStr = str_ireplace("WORLD", "PHP", $str);
echo $newStr; // Output: Hello, PHP!Using str_ireplace() performs a case‑insensitive replacement.
Conclusion
The str_replace() function is a flexible tool for PHP developers, capable of handling single or multiple replacements and offering case‑insensitive options via str_ireplace() . Mastering it simplifies string operations in backend development.
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.