Using str_replace in PHP: Basic and Advanced Examples

This tutorial explains PHP's str_replace function, demonstrating simple string replacement, array‑based replacements, and a less common usage where both search and replace parameters are arrays, with example outputs and screenshots illustrating each case.

php Courses
php Courses
php Courses
Using str_replace in PHP: Basic and Advanced Examples

In this article the author explains the PHP function str_replace, which performs case‑sensitive string replacement, and demonstrates several usage patterns found while reading the ThinkPHP framework source.

The first example shows a simple replacement where the word “world” in the string “Hello world!” is replaced by “Peter”, producing “Hello Peter!”.

The second example extends the function to replace multiple occurrences using arrays, showing how the function can replace each element of a search array with the corresponding element of a replace array and reporting the number of replacements performed.

The third example illustrates a less common usage where both the search and replace arguments are arrays, a technique discovered in the framework’s source code for generating SQL statements.

Each example is accompanied by screenshots of the controller output and the resulting transformed strings.

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.

TutorialString 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.