Using PHP str_replace() for String Replacement

This article explains the PHP str_replace() function, its syntax, parameters, return value, and provides multiple code examples demonstrating single, multiple, and case‑insensitive string replacements.

php Courses
php Courses
php Courses
Using PHP str_replace() for String Replacement

String manipulation is a common task in PHP, 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 processes 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 all replacements have been applied.

Below are several usage examples.

Example 1: Replace a single character

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

In this example, the word "World" is replaced with "PHP", and the result is printed.

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 demonstrates replacing both "Hello" and "World" with "Hi" and "PHP" respectively.

Example 3: Case‑insensitive replacement

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

Here str_ireplace() is used to replace "world" regardless of its case.

Summary

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

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

programmingPHPstring-replacementstr_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

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.