Using PHP str_replace() for String Replacement: 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 for single, multiple, and case‑insensitive replacements, helping developers master string manipulation in PHP.
In PHP, string manipulation is a common task, and the str_replace() function is one of the most frequently used functions for replacing specific characters or substrings.
The syntax of str_replace() is:
str_replace(search, replace, subject)Parameter description:
search : The character or string to be replaced; it can be an array, in which case the function will replace each element in order.
replace : The replacement character or string; if search is an array, replace must also be an array with the same number of elements.
subject : The target string on which the replacement is performed.
Return value
The function returns the string after the replacements have been applied.
Below are usage examples demonstrating how to apply str_replace() in different scenarios.
Example 1: Replace a single character
$str = "Hello, World!";
$newStr = str_replace("World", "PHP", $str);
echo $newStr; // Output: Hello, PHP!This example replaces the word "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!Here both "Hello" and "World" are replaced simultaneously, producing "Hi, PHP!".
Example 3: Replace characters while ignoring case
$str = "Hello, world!";
$newStr = str_ireplace("WORLD", "PHP", $str);
echo $newStr; // Output: Hello, PHP!This example uses str_ireplace() to replace "world" regardless of its case, resulting in "Hello, PHP!".
Summary
The str_replace() function is a vital tool in PHP for replacing specific characters or substrings. It is flexible, allowing single or multiple replacements and can ignore case when needed. Mastering str_replace() enables developers to perform string operations more efficiently; be mindful of parameter order and data types to avoid unexpected results, and practice extensively to become proficient.
Java learning resources
C language learning resources
Frontend learning resources
C++ learning resources
PHP learning resources
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.