str_replace

Replace all occurrences of the search string with the replacement string

Syntax

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

Parameters

search

The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

replace

The replacement value that replaces found search values. An array may be used to designate multiple replacements.

subject

The string or array being searched and replaced on, otherwise known as the haystack. If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

count

If passed, this will be set to the number of replacements performed.

Return

This function returns a string or an array with the replaced values.

Examples

search replace subject

<?

$search = "case";
$replace = "replace";
$subject = "case Case CASE";

$return = str_replace($search, $replace, $subject);

echo $return;

?>
replace Case CASE

count

<?

$search = "case";
$replace = "replace";
$subject = "case Case CASE";

$return = str_replace($search, $replace, $subject, $count);

echo $count;

?>
1

1

<?

$search = array("search1", "search2", "search3");
$replace = "replace";
$subject = "search1 search2 search3";

$return = str_replace($search, $replace, $subject);

echo $return;

?>
replace replace replace

2

<?

$search = array("search1", "search2", "search3");
$replace = array("replace1", "replace2", "replace3");
$subject = "search1 search2 search3";

$return = str_replace($search, $replace, $subject);

echo $return;

?>
replace1 replace2 replace3

3

<?

$search = array("\r\n", "\n", "\r"); // \r\n first
$replace = "<br>";
$subject = "line\nline\rline\r\nline";

$return = str_replace($search, $replace, $subject);

echo $return;

?>
line<br>line<br>line<br>line

4

<?

$search = array('a', 'b', 'c', 'd', 'e');
$replace = array('b', 'c', 'd', 'e', 'f');
$subject = 'a';

$return = str_replace($search, $replace, $subject);

echo $return;

?>
f

5

<?

$search = array('a', 'p');
$replace = array('apple', 'pear');
$subject = 'apricot';

$return = str_replace($search, $replace, $subject);

echo $return;

?>
apearpearlepearricot

Internal

str_ireplace

External

PHP

Home Menu