Backend Development 3 min read

Using PHP str_replace() for String Replacement – Syntax, Parameters, and Examples

This article explains PHP's str_replace() function, detailing its syntax, parameters, return value, and provides three practical code examples demonstrating single-character replacement, multiple replacements using arrays, and case‑insensitive replacement with str_ireplace(), helping developers perform flexible string manipulations.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP str_replace() for String Replacement – Syntax, Parameters, and Examples

In PHP, string manipulation is a common task, 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)

Parameters:

search : the value to be replaced; can be a string or an array.

replace : the replacement value; must be of the same type and length as search when arrays are used.

subject : the target string or array of strings.

The function returns the string after replacement.

Example 1 – Replacing a single character:

$str = "Hello, World!";
$newStr = str_replace("World", "PHP", $str);
echo $newStr; // 输出:Hello, PHP!

Example 2 – Replacing multiple characters using arrays:

$str = "Hello, World!";
$search = array("Hello", "World");
$replace = array("Hi", "PHP");
$newStr = str_replace($search, $replace, $str);
echo $newStr; // 输出:Hi, PHP!

Example 3 – Case‑insensitive replacement using str_ireplace() :

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

In summary, str_replace() is a flexible and essential function for PHP developers, capable of handling single or multiple replacements and offering case‑insensitive options via str_ireplace() . Proper understanding of its parameters and return value enables efficient string processing.

Backend DevelopmentPHPcode examplesstring-manipulationstr_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.