Understanding PHP str_replace(): Syntax, Parameters, and Practical Examples

This article explains the PHP str_replace() function, detailing its syntax, the roles of search, replace, and subject parameters, and demonstrates four common usage patterns—including string-to-string, array-to-string, array-to-array replacements, and counting replacements—while highlighting replacement order effects.

php Courses
php Courses
php Courses
Understanding PHP str_replace(): Syntax, Parameters, and Practical Examples

The str_replace() function in PHP replaces occurrences of a search string with a replacement string within a given subject.

Syntax:

str_replace(mixed $search, mixed $replace, mixed $subject [, int &$count]) : mixed

1. Both $search and $replace are strings:

<?php
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
echo $bodytag; // outputs: <body text='black'>
?>

2. $search is an array, $replace is a string:

<?php
$vowels = array("a","e","i","o","u","A","E","I","O","U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
echo $onlyconsonants; // outputs: Hll Wrld f PHP
?>

3. Both $search and $replace are arrays:

<?php
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits","vegetables","fiber");
$yummy   = array("pizza","beer","ice cream");
$newphrase = str_replace($healthy, $yummy, $phrase);
// outputs: You should eat pizza, beer, and ice cream every day
?>

4. Using the optional $count parameter to get the number of replacements:

<?php
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count; // 2
?>

Note on replacement order: When both $search and $replace are arrays, replacements are performed sequentially from left to right, so earlier replacements can affect later ones. For example:

$search  = array('A','B','C','D','E');
$replace = array('B','C','D','E','F');
$subject = 'A';
echo str_replace($search, $replace, $subject); // outputs: F
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.

BackendCode Examplesstring-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.