Categories
PHP

PHP str_replace

str_replace — Replace all occurrences of the search string with the replacement string

Description


str_replace ( array|string $search , array|string $replace , string|array $subject [, int &$count = null ] ) : string|array

If you don’t need fancy replacing rules (like regular expressions), you should use this function instead of preg_replace().

This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.

Examples

Example #1 Basic str_replace() examples

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

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

// Provides: You should eat pizza, beer, and ice cream every day
$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);

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

Leave a Reply

Your email address will not be published. Required fields are marked *