Be careful when replacing characters (or repeated patterns in the FROM and TO arrays):
For example:
<?php
$arrFrom = array("1","2","3","B");
$arrTo = array("A","B","C","D");
$word = "ZBB2";
echo str_replace($arrFrom, $arrTo, $word);
?>
I would expect as result: "ZDDB"
However, this return: "ZDDD"
(Because B = D according to our array)
To make this work, use "strtr" instead:
<?php
$arr = array("1" => "A","2" => "B","3" => "C","B" => "D");
$word = "ZBB2";
echo strtr($word,$arr);
?>
This returns: "ZDDB"
str_replace
(PHP 4, PHP 5)
str_replace — Remplace toutes les occurrences dans une chaîne
Description
str_replace() retourne une chaîne ou un tableau, dont toutes les occurrences de search dans subject ont été remplacées par replace .
Si vous n'avez pas besoin de règles de remplacement compliquées (comme les expressions rationnelles), utilisez cette fonction de préférence à ereg_replace() et preg_replace().
Liste de paramètres
Si search et replace sont des tableaux, alors str_replace() prendra une valeur de chaque tableau, et l'utilisera pour faire le remplacement dans subject . Si replace a moins de valeurs que search , alors une chaîne vide sera utilisée pour effectuer les remplacements. Si search est un tableau et que replace est une chaîne, alors la chaîne de remplacement sera utilisée pour chaque élément de search . Cependant, l'inverse n'aurait aucun sens.
Si search ou replace sont des tableaux, les éléments sont traités du premier, au dernier.
- search
-
- replace
-
- subject
-
Si subject est un tableau, alors le remplacement se fera sur chaque élément de celui-ci, et la valeur retournée sera aussi un tableau.
- count
-
Note: Si fourni, contiendra le nombre de recherches et d'occurrences à remplacer.
Valeurs de retour
Cette fonction retourne une chaîne, ou un tableau, contenant les valeurs remplacées.
Historique
| Version | Description |
|---|---|
| 5.0.0 | Ajout du paramètre count . |
| 4.3.3 | Le comportement de cette fonction a changée. Dans les version précédentes, un bogue existait lors de l'utilisation de tableaux avec les paramètres search et replace en même temps. Les index de search qui étaient vides étaient ignorés, mais le pointeur interne de replace n'étais pas incrémenté. Cela a été corrigé en PHP 4.3.3, tout script s'appuyant sur ce bogue, doit supprimer les entrées vides avant d'appeler cette fonction pour imiter le comportement d'origine. |
| 4.0.5 | Le plupart des paramètres peut maintenant être un tableau. |
Exemples
Exemple #1 Exemple avec str_replace()
<?php
// Génère : <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
// Génère : Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
// Génère : 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);
// Utilisation du compteur d'occurrences en PHP 5.0.0
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count; // 2
// Ordre des remplacements
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order = array("\r\n", "\n", "\r");
$replace = '<br />';
// Traitement du premier \r\n, ils ne seront pas convertis deux fois.
$newstr = str_replace($order, $replace, $str);
// Affiche : apearpearle pear
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;
?>
Notes
Note: Cette fonction gère les chaînes binaires.
Note: Cette fonction est sensible à la casse. Utilisez la fonction str_ireplace() pour un remplacement insensible à la casse.
Voir aussi
- str_ireplace() - Version insensible à la casse de str_replace
- substr_replace() - Remplace un segment dans une chaîne
- preg_replace() - Rechercher et remplacer par expression rationnelle standard
- strtr() - Remplace des caractères dans une chaîne
str_replace
16-Jun-2009 02:44
21-May-2009 04:49
<?php
/*
This is a function for made recursive str_replaces in an array
*/
function recursive_array_replace($find, $replace, &$data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
if (is_array($value)) {
recursive_array_replace($find, $replace, $data[$key]);
} else {
$data[$key] = str_replace($find, $replace, $value);
}
}
} else {
$data = str_replace($find, $replace, $data);
}
}
$a = array();
$a['a'] = "a";
$a['b']['a'] = "ba";
$a['b']['b'] = "bb";
$a['c'] = "c";
$a['d']['a'] = "da";
$a['d']['b'] = "db";
$a['d']['c'] = "dc";
$a['d']['d'] = "dd";
echo "Before Replaces";
print_r($a);
recursive_array_replace("a", "XXXX", $a);
echo "After Replaces";
print_r($a);
?>
13-May-2009 05:25
I create a little function to transform "User@example.net" [to] "user AT example DOT net" and conversely.
<?php
function code_mail($email) {
if(preg_match('`^.+@.+\..{1,5}$`', $email)) { //email format
$email = str_replace('.', ' DOT ', $email); //replace . by dot
$email = str_replace('@', ' AT ', $email); //replace @ by at
return $email;
}
else { //not email format
return false;
}
}
function decode_mail($email) { //on décode...
$email = str_replace(' DOT ', '.', $email); //replace dot by .
$email = str_replace(' AT ', '@', $email); //replace at by @
return $email;
}
?>
20-Mar-2009 02:03
This is a function that filters a filename for nicer URLs. It doesn't turn the whole filename to lowercase (easy mod):
<?php
/*
* Devuelve el nombre del archivo filtrado de la siguiente manera:
* Los espacios sustituidos por '-'
* Los acentos se quitan de las vocales
* 'n' en vez de 'ñ'
* Cualquier otro caracter especial diferente de ('_', '-', '.') se elimina
*/
function preparar_nom_archivo($nom_archivo)
{
$arr_busca = array(' ','á','à','â','ã','ª','Á','À',
'Â','Ã', 'é','è','ê','É','È','Ê','í','ì','î','Í',
'Ì','Î','ò','ó','ô', 'õ','º','Ó','Ò','Ô','Õ','ú',
'ù','û','Ú','Ù','Û','ç','Ç','Ñ','ñ');
$arr_susti = array('-','a','a','a','a','a','A','A',
'A','A','e','e','e','E','E','E','i','i','i','I','I',
'I','o','o','o','o','o','O','O','O','O','u','u','u',
'U','U','U','c','C','N','n');
$nom_archivo = trim(str_replace($arr_busca, $arr_susti, $nom_archivo));
return ereg_replace('[^A-Za-z0-9\_\.\-]', '', $nom_archivo);
}
?>
(you may delete the line breaks in the arrays) Sorry for the spanish. In english: Substitutes spaces with '-', accents turn into vocals, 'ñ' to 'n', deletes weird characters except ('_', '-', '.').
Cheers
24-Feb-2009 01:58
In order to create nicer urls i use this simple function:
<?php
function niceURL($string)
{
$que = array( 'á','é','í','ó','ú','Á','É','Í','Ó','Ú','ñ','Ñ',' ' );
$por = array( 'a','e','i','o','u','A','E','I','O','U','n','n','-' );
return strtolower( str_replace( $que,$por,$string ) );
}
?>
For string "Hello Cruel World"
This will return "hello-cruel-world"
However once i wrote this:
<?php
function niceURL($string)
{
//changing the place of ' ' by '-' to the begining
$que = array( ' ','á','é','í','ó','ú','Á','É','Í','Ó','Ú','ñ','Ñ' );
$por = array( '-','a','e','i','o','u','A','E','I','O','U','n','n' );
return strtolower( str_replace( $que,$por,$string ) );
}
?>
And for "Hello Cruel World"
This will return "hellocruelworld"
I have no idea why but it made me crazy for a while,
08-Feb-2009 09:41
simple bbcode
<?php
function bbcode($msg){
//bold
$msg = str_replace("[b]", "<b>", $msg);
$msg = str_replace("[/b]", "</b>", $msg);
//italic
$msg = str_replace("[i]", "<i>", $msg);
$msg = str_replace("[/i]", "</i>", $msg);
//image
$msg = str_replace("[img]", "<img src=\"", $msg);
$msg = str_replace("[/img]", "\" />", $msg);
#$msg = str_replace("", "", $msg);
return ($msg);
}
?>
03-Feb-2009 10:16
For those wanting a quick solution to replacing a string a certain number of times, starting from the left, this might be a solution:
<?php
echo implode("replace term", explode("search term", "input", $limit));
?>
Hope this helps.
29-Jan-2009 02:38
As previous commentators mentioned, when $search contains values that occur earlier in $replace, str_replace will factor those previous replacements into the process rather than operating solely on the original string. This may produce unexpected output.
Example:
<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'ABCDE';
echo str_replace($search, $replace, $subject); // output: 'FFFFFF'
?>
In the above code, the $search and $replace should replace each occurrence in the $subject with the next letter in the alphabet. The expected output for this sample is 'BCDEF'; however, the actual output is 'FFFFF'.
To more clearly illustrate this, consider the following example:
<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject); // output: 'F'
?>
Since 'A' is the only letter in the $search array that appears in $subject, one would expect the result to be 'B'; however, replacement number $n does *not* operate on $subject, it operates on $subject after the previous $n-1 replacements have been completed.
The following function utilizes array_combine and strtr to produce the expected output, and I believe it is the most efficient way to perform the desired string replacement without prior replacements affecting the final result.
<?php
/**
* When using str_replace(...), values that did not exist in the original string (but were put there by previous
* replacements) will be replaced continuously. This string replacement function is designed replace the values
* in $search with those in $replace while not factoring in prior replacements. Note that this function will
* always look for the longest possible match first and then work its way down to individual characters.
*
* The "o" in "stro_replace" represents "original", indicating that the function operates only on the original string.
*
* @param array $search list of strings or characters that need to be replaced
* @param array $replace list of strings or characters that will replace the corresponding values in $search
* @param string $subject the string on which this operation is being performed
*
* @return string $subject with all substrings in the $search array replaced by the values in the $replace array
*/
function stro_replace($search, $replace, $subject)
{
return strtr( $subject, array_combine($search, $replace) );
}
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'ABCDE';
echo stro_replace($search, $replace, $subject); // output: 'BCDEF'
?>
Some other examples:
<?php
$search = array(' ', '&');
$replace = array(' ', '&');
$subject = 'Hello & goodbye!';
// We want to replace the spaces with and the ampersand with &
echo str_replace($search, $replace, $subject); // output: "Hello&nbsp&&nbspgoodbye!" - wrong!
echo stro_replace($search, $replace, $subject); // output: "Hello & goodbye!" - correct!
/*
Note: Run the above code in the CLI or view source on your web browser - the replacement strings for stro_replace are HTML entities which the browser interprets.
*/
?>
<?php
$search = array('ERICA', 'AMERICA');
$replace = array('JON', 'PHP');
$subject = 'MIKE AND ERICA LIKE AMERICA';
// We want to replace the name "ERICA" with "JON" and the word "AMERICA" with "PHP"
echo str_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE AMJON", which is not correct
echo stro_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE PHP", which is correct
?>
12-Jan-2009 03:35
Came across a difference between Excel 2003 vs Excel 2007 documents and the different formats they push out csv files.
In 2007, the format pushes out the chr(13) instead of the \n in 2003.
Just as a safety precaution, do a quick replace on the fread contents from the excel file :-)
<?php
$lineseparator = "\n";
// check for the user supplied list type format
if ($_REQUEST['listtype'] == "csv")
$fieldseparator = ",";
elseif ($_REQUEST["listtype"] == "tab")
$fieldseparator = "\t";
// replaces the carriage return with the \n character
$csvcontent = str_replace(chr(13), $lineseparator,$csvcontent);
// then
foreach(split($lineseparator,$csvcontent) as $line) {
$lines++;
if ($lines >1) { // skips header row
$line = trim($line," \t");
$line = str_replace("\r","",$line);
// split the line up
$linearray = explode($fieldseparator,$line);
// take care of The "Billy" the kid issue
for ($x = 0; $x<sizeof($linearray); $x++) {
$linearray[$x] = str_replace('""','^',$linearray[$x]);
$linearray[$x] = str_replace('""','^',$linearray[$x]);
$linearray[$x] = str_replace('"','',$linearray[$x]);
$linearray[$x] = str_replace('"','',$linearray[$x]);
$linearray[$x] = str_replace('^','"',$linearray[$x]);
}
// then reference each element in order of the line by array and key
// echo $linearray[0]; //, etc.
}
}
?>
Happy Coding!
09-Jan-2009 06:27
I´ve just made gabriel dot totoliciu at ddnet dot ro's function a little smaller, hope you like it.
NOTE: this function is not 100% secure, since the subject can have the temp replace
<?php
function stru_replace($search, $replace, $subject){
if(!is_array($search)) {
$search = array($search);
}
if(!is_array($replace)){
$replace = array($replace);
}
foreach($search as $key => $value){
//used "|{}#PHP_IsAwesome" to try make the temp replace secure, the bigger the better
$subject = str_replace($value, "|{}#PHP_IsAwesome".$key."|{}#PHP_IsAwesome", $subject);
}
foreach($search as $key => $value){
$subject = str_replace("|{}#PHP_IsAwesome".$key."|{}#PHP_IsAwesome", $replace[$key], $subject);
}
return($subject);
}
?>
07-Dec-2008 12:48
Substituindo caracteres acentuados em uma string (português)
If you need change portugues chars to ansi chars, try this
$com_acentos=array(
"á","Á","ã","Ã",
"â","Â","à","À",
"é","É","ê","Ê",
"í","Í","ó","Ó",
"õ","Õ","ô","Ô",
"ú","Ú","ü","Ü",
"ç","Ç");
$sem_acentos=array(
"a","A","a","A",
"a","A","a","A",
"e","E","e","E",
"i","I","o","O",
"o","O","o","O",
"u","U","u","U",
"c","C");
$input_string = 'Ações em Alta. Série positiva:[áéíóúÁÉÍÓÚçÇ]';
$output_string = str_replace($com_acentos,$sem_acentos,$input_string);
echo 'input_string : ' . $input_string . " <br />\n";
echo 'output_string: ' . $output_string . " <br />\n";
-------------------
Your will get:
input_string : Ações em Alta. Série positiva:[áéíóúÁÉÍÓÚçÇ]
output_string: Acoes em Alta. Serie positiva:[aeiouAEIOUcC]
07-Dec-2008 03:30
As 'max at efoxdesigns dot com' said, when you try to replace a string that occurs in the $search array after the same character occurs in the $replace character, you don't usually get what you want.
examples:
<?php
$search=array("beer", "graffiti", "programming");
$replace=array("graffiti", "motorcycles", "chips");
$string="I like beer, graffiti and programming.";
var_dump(str_replace($search, $replace, $string));
// you would expect to see:
// string(39) "I like graffiti, motorcycles and chips."
// well.. what you actually see is:
// string(42) "I like motorcycles, motorcycles and chips."
?>
I've made a function (stru_replace) that replaces everything correctly. It has some downsides, as it does not implement all the functionality of str_replace:
<?php
$search=array("beer", "graffiti", "programming");
$replace=array("graffiti", "motorcycles", "chips");
$string="I like beer, graffiti and programming.";
var_dump(str_replace($search, $replace, $string));
//string(39) "I like graffiti, motorcycles and chips."
?>
I'm sure that the functions can be improved. Anyway, I guess they are a bit useful :D
<?php
//returns the key of the minimum value within the array
function minkey($array)
{
$first=true;
$mkey=false;
$mvalue=false;
foreach($array as $key=>$value)
{
if (is_numeric($value))
{
if ($mvalue>$value || $first)
{
$mvalue=$value;
$mkey=$key;
if ($first) $first=false;
}
}
}
return $mkey;
}
//returns the key and the position of the first needle found withing the (string)haystack
function strposfirst($haystack, $needles, $currentpos=0)
{
$positions=array();
foreach($needles as $key=>$value)
$positions[$key]=strpos($haystack,$value,$currentpos);
$minkey=minkey($positions);
if ($minkey===false) return array(false, false);
return array($minkey, $positions[$minkey]);
}
//third parameter must be a string
function stru_replace($search, $replace, $string)
{
$newString="";
// the function only implements functionality for the $search and $replace parameters
// as arrays that have the same ammount of elements
if (is_array($search) && is_array($replace))
{
if (count($search)!=count($replace))
throw new ErrorException("The \$search and \$replace parameters must have the same number of elements");
$oCPos=0; // current position inside old string
$done=false; // determines when we searched all the string
while(!$done)
{
//get the key and position of the first found element
list($key, $position)=strposfirst($string, $search, $oCPos);
//if there is a found element, get concatenate the string before it, and replace the string
if ($position!==false)
{
// the string before the needle is concatenated in the new string
$newString.=substr($string, $oCPos, $position-$oCPos);
// the needle is replaced
$newString.=$replace[$key];
//add the with of the length of the string before the needle + the length of the new key
$oCPos+=$position-$oCPos+strlen($search[$key]);
}
//set the done flag when nothing is found (position is false)
else $done=true;
}
//concatenate the string after the last needle
$newString.=substr($string, $oCPos);
return $newString;
}
else return str_replace($search, $replace, $string);
}
?>
I hope this helps :)
If I'll change the functions, you'll find them here
http://pb.dev.ddnet.ro/phpLecture/issue1.php
02-Dec-2008 10:55
Replacement for str_replace in which a multiarray of numerically keyed data can be properly evaluated with the given template without having a search for 11 be mistaken for two 1's next to each other
<?php
function data_template($input, $template) {
if ($template) { // template string
if ($split = str_split($template)) { // each char as array member
foreach ($split as $char) { // each character
if (is_numeric($char)) { // test for digit
if ($s != 1) { // new digit sequence
$i++;
$s = 1;
}
$digits[$i] .= $char; // store digit
} else { // not a digit
if ($s != 2) { // new non-digit sequence
$i++;
$s = 2;
}
$strings[$i] .= $char; // store string
}
}
if ($i && $input && is_array($input)) { // input data
foreach ($input as $sub) { // each subarray
if (is_array($sub)) {
$out = ''; // reset output
for ($j = 0; $j <= $i; $j++) { // each number/string member
if ($number = $digits[$j]) { // number
$out .= $sub[$number]; // add value from subarray to output
} else { // string
$out .= $strings[$j]; // add to output
}
}
$a[] = $out;
}
}
return $a;
} // input
} // split
} // template
}
$input = array(array(1=>'yellow', 2=>'banana', 11=>'fruit'), array(1=>'green', 2=>'spinach', 11=>'vegetable'), array(1=>'pink', 2=>'salmon', 11=>'fish'));
print_r (data_template($input, '2: a 1, healthy 11'));
/*
Array
(
[0] => banana: a yellow, healthy fruit
[1] => spinach: a green, healthy vegetable
[2] => salmon: a pink, healthy fish
)
*/
// str_replace would have wanted to output 'banana: a yellow, healthy yellowyellow
?>
Not sure if this will help anyone but I wrote it for my application and thought I would share just in case
29-Oct-2008 11:01
Well, suffering without parameter replace ability like in plsql
sql = > "select * from x where id = %1";
execute sql, var1;
(sorry for pseudo)
here is a function just wrote for my self using str_replace, let me know if there is a better way for such generic function
<?php
function sql_prep()
{
$args = func_get_args();
$sql = array_shift($args);
$args_cnt = func_num_args();
$found=0;
foreach($args as $key=>$value)
{
$rep_str = "\$sql = str_replace('%$key','$value',\$sql,\$count);";
eval($rep_str);
if($count)
{
$found++;
}
}
if($found == $args_cnt-1)
{
return $sql;
}
else
{
echo "WARNING: number of subs=".($args_cnt-1)." does not match number of reps=$found";
return $sql;
}
}
?>
16-Oct-2008 06:42
<?php
// Function used to "Genderize" a phrase, replacing "[he]" with "she", if gender is female,
// and "[he]" with "he" if gender is male, and "[she]" with "he" if gender is male, etc...
function GenderizePhrase($Phrase='', $Gender="male"){
$SearchValues = array(
"[He]",
"[he]",
"[He's]",
"[he's]",
"[She]",
"[she]",
"[She's]",
"[she's]",
"[Him]",
"[him]",
"[Her]",
"[her]",
"[His]",
"[his]",
"[Hers]",
"[hers]",
"[Her's]",
"[her's]",
"[Himself]",
"[himself]",
"[Herself]",
"[Herself]"
);
if($Gender=="Male" ||$Gender=="male" || $Gender == 1){
// Replace phrase pieces with male versions
$ReplacementValues = array(
"He",
"he",
"He's",
"he's",
"He",
"he",
"He's",
"he's",
"Him",
"him",
"His",
"his",
"His",
"his",
"His",
"his",
"His",
"his",
"Himself",
"himself",
"Himself",
"himself"
);
}else{
// Replace phrase pieces with female versions
$ReplacementValues = array(
"She",
"she",
"She's",
"she's",
"She",
"she",
"She's",
"she's",
"Her",
"her",
"Her",
"her",
"Hers",
"hers",
"Hers",
"hers",
"Her's",
"her's",
"Herself",
"herself",
"Herself",
"Herself"
);
}
return str_replace($SearchValues, $ReplacementValues, $Phrase);
}
?>
16-Oct-2008 05:49
This function is made in order to slove the problem when using conventional str_replace built-in function when inserting tags in normal string.
<?php
$what : string to be matched wholly
$where : string to be searched in
$tag_open : opening tag string such as <font color=#123456>
$tag_close : closing tag string such as </font>
function str_html_addtag($what, $where, $tag_open, $tag_close)
{
$array_pos_begin = array();
$array_pos_end = array();
for($cnt=0; $cnt<sizeof($what); $cnt++)
{
$pos = 0;
$pos_start = $pos;
while($pos = stripos($where, $what[$cnt], $pos))//stripos - case-insensitive search
{
if(is_false($pos)) break;
array_push($array_pos_begin, $pos);
array_push($array_pos_end, $pos+strlen($what[$cnt]));
if(sizeof($array_pos_begin)>10) break;
$pos++;
}
}
array_multisort($array_pos_begin, $array_pos_end);
for($i=0; $i<sizeof($array_pos_begin)-1; $i++)
{
if($array_pos_end[$i]>=$array_pos_begin[$i+1])
{
$array_pos_end[$i] = max($array_pos_end[$i], $array_pos_end[$i+1]);
array_splice($array_pos_begin, $i+1, -(sizeof($array_pos_begin)-($i+2)));
array_splice($array_pos_end, $i+1, -(sizeof($array_pos_end)-($i+2)));
$i--;
}
}
for($i=sizeof($array_pos_begin)-1; $i>=0; $i--)
{
$head = substr($where, 0, $array_pos_end[$i]);
$tail = substr($where, $array_pos_end[$i]);
$where = $head.$tag_close.$tail;
$head = substr($where, 0, $array_pos_begin[$i]);
$tail = substr($where, $array_pos_begin[$i]);
$where = $head.$tag_open.$tail;
}
return $where;
}
?>
06-Oct-2008 11:12
I tried max at efoxdesigns dot com solution for str_replace_once but it didn't work quite right so I came up with this solution (all params must be strings):
<?php
function str_replace_once($search, $replace, $subject) {
$firstChar = strp