Backend Development 4 min read

Using PHP str_replace() for String Replacement

This article explains PHP's str_replace() function, detailing its syntax, parameters, return value, and provides three practical code examples—including single and multiple replacements and case‑insensitive replacement—while highlighting best practices for effective string manipulation.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP str_replace() for String Replacement

In PHP, string manipulation is a common task, and the str_replace() function is a widely used tool for replacing specific characters or substrings within a string.

The syntax of str_replace() is:

str_replace(search, replace, subject)

Parameter description:

search : The character(s) or string(s) to be replaced. It can be an array, in which case the function processes each element sequentially.

replace : The replacement character(s) or string(s). If search is an array, replace must also be an array of the same length.

subject : The target string on which the replacement is performed.

Return value:

The function returns the string after performing the replacements.

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 with "Hi" and "PHP" respectively.

Example 3: Replace characters case‑insensitively

$str = "Hello, world!";
$newStr = str_ireplace("WORLD", "PHP", $str);
echo $newStr; // Output: Hello, PHP!

The str_ireplace() function performs a case‑insensitive replacement, so the word "world" is replaced regardless of its case.

Conclusion

The str_replace() function is a powerful and flexible tool for string replacement in PHP, capable of handling single or multiple replacements and offering case‑insensitive options via str_ireplace() . Mastering this function enables developers to perform efficient string manipulations.

Additional learning resources are provided through links to Java, C, C++, frontend, and PHP study materials.

BackendPHPstring replacementphp tutorialstr_replace
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.