Backend Development 4 min read

Using PHP str_replace() Function: Syntax, Examples, and Applications

This article explains the PHP str_replace() function, its syntax, parameters, and demonstrates various usage examples including simple string replacement, array-based replacements, URL and HTML tag modifications, and mentions related functions like preg_replace().

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP str_replace() Function: Syntax, Examples, and Applications

PHP is a popular server‑side scripting language often used for web development. One of its many built‑in functions is str_replace() , which replaces substrings within a string.

The syntax of str_replace() is:

str_replace($search, $replace, $subject)

Here $search is the substring to be replaced, $replace is the replacement string, and $subject is the original string. All three parameters can be either strings or arrays, allowing multiple replacements in a single call.

Simple example: replace the word "world" with "PHP".

$oldstr = "Hello, world!";
$newstr = str_replace("world", "PHP", $oldstr);
echo $newstr;

Output:

Hello, PHP!

Beyond single words, str_replace() can replace punctuation, numbers, or any other substrings.

Array replacement example:

$oldstr = "Hello, my name is John.";
$search = array(",", "John");
$replace = array(";", "Peter");
$newstr = str_replace($search, $replace, $oldstr);
echo $newstr;

Output:

Hello; my name is Peter.

To replace all matches, you can use preg_replace() instead of str_replace() .

Example of replacing a domain in a URL:

$url = "http://www.example.com/index.php?id=1";
$newurl = str_replace("example.com", "mywebsite.com", $url);
echo $newurl;

Output:

http://www.mywebsite.com/index.php?id=1

Similarly, str_replace() can be used to replace HTML tags. The following code replaces and tags with and respectively.

$html = "
Hello
,
world
!
";
$newhtml = str_replace(array("
", "
", "
", "
"),
                       array("
", "
", "
", "
"),
                       $html);
echo $newhtml;

Output:

Hello
,
world
!

In summary, the str_replace() function is a versatile tool for string manipulation in PHP, useful for a wide range of tasks in web development.

BackendPHPtutorialstring 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

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.