Using str_replace() in PHP: Syntax, Parameters, and Examples
This article explains PHP's str_replace() function, covering its syntax, parameter details, return value, and providing three practical code examples—including single, multiple, and case‑insensitive replacements—to help developers master flexible string manipulation in backend development.
In PHP, string manipulation is common, and the str_replace() function is widely used to replace specific characters or substrings within a string.
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 of strings.
replace : the replacement value; can be a string or an array that must correspond to search when both are arrays.
subject : the target string or array of strings on which the replacement is performed.
Return value:
The function returns the string after all replacements have been applied.
Example 1: Replacing a single substring
$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: Replacing multiple substrings
$str = "Hello, World!";
$search = array("Hello", "World");
$replace = array("Hi", "PHP");
$newStr = str_replace($search, $replace, $str);
echo $newStr; // Output: Hi, PHP!Here both "Hello" and "World" are replaced simultaneously.
Example 3: Case‑insensitive replacement
$str = "Hello, world!";
$newStr = str_ireplace("WORLD", "PHP", $str);
echo $newStr; // Output: Hello, PHP!The str_ireplace() function performs a case‑insensitive replacement.
Summary
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 its parameters and usage can greatly simplify string manipulation tasks.
Additional learning resources:
Java learning material
C language learning material
Frontend learning material
C++ learning material
PHP learning material
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.