Recent changes Random page
GAMING
Technology
 
Gaming
Entertainment
Science Fiction
Biggest wikis
Hobbies
Music
See more...

str_replace

from PHPWiki - the free guide to PHP.

Jump to: navigation, search


[edit] Description

str_replace returns an string or an array of an string with all occurances of the search value(s) replaced with the replace value(s).

Note: From version 4.0.5 of php onwards, all parameters can be arrays. However, due to a bug involved with arrays for both search and replace parameters, it is advised that arrays only be used in version 4.33 or later.

[edit] Parameters

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

[edit] Parameter Infos

Parameter PHP Version Type
str_replace 4 or 5 returns string or array
search 4 or 5 string or array (PHP >4.0.5)
replace 4 or 5 string or array (PHP >4.0.5)
subject 4 or 5 string or array (PHP >4.0.5)
count 5 integer


[edit] Examples

[edit] Example 1 (Simple):

<?php
 // Replace spaces with underscores
 $bodytag = str_replace(" ", "_", "Str replace");
?>

Note where Str replace is, you can use a variable there aswell.

[edit] Output

Str_replace


[edit] Example 2 (The use of arrays):

<?php
 $phrase  = "I love classic music and to listen to the strings at the opera.";
 $search  = array("classic", "strings", "opera");
 $replace = array("techno",  "beats",   "disco");
 echo str_replace($search, $replace, $phrase);
?>

[edit] Output

I love techno music and to listen to the beats at the disco.


[edit] See also

str_ireplace, substr_replace, preg_replace, and strtr

For more details on this function, visit its entry in the php manual.
Rate this article:
Share this article: