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.
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
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.