Using str_replace() in PHP: 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—including single, multiple, and case‑insensitive replacements—to help developers master string manipulation in backend development.

php Courses
php Courses
php Courses
Using str_replace() in PHP: 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.

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. replace: the replacement value; can be a string or an array (must match the size of search when both are arrays). subject: the target string on which the replacement is performed.

Return value:

The function returns the string after replacement.

Example 1: Replace a single character

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

This example replaces "World" with "PHP" and prints the result.

Example 2: Replace multiple characters

$str = "Hello, World!";<br/>$search = array("Hello", "World");<br/>$replace = array("Hi", "PHP");<br/>$newStr = str_replace($search, $replace, $str);<br/>echo $newStr; // Output: Hi, PHP!

This example replaces "Hello" with "Hi" and "World" with "PHP".

Example 3: Case‑insensitive replacement

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

Using str_ireplace() performs a case‑insensitive replacement.

Conclusion

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 it simplifies string operations in backend development.

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.

BackendTutorialstring-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

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.