Compress a string's internal spaces:
<?php
$str = ' This is a test ';
$count = 1;
while($count)
$str = str_replace(' ', ' ', $str, $count);
?>
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
01-Nov-2009 04:22
15-Oct-2009 08:41
As mentioned earlier you should take the order into account when substituting multiple values.
However it is worth noticing that str_replace doesn't seem to re-read the string when doing single replacements. Take the following example.
<?php
$s = '/a/a/';
$s = str_replace('/a/', '/', $s);
?>
You would expect the following.
First replacement '/a/a/' -> '/a/'
Second replacement '/a/'->'/'
This is not the case, the actual result will be '/a/'.
To fix this, you will have to put str_replace in a while-loop.
<?php
$s = '/a/a/';
while(strpos($s, '/a/') !== false)
$s = str_replace('/a/', '/', $s); //eventually $s will == '/'
?>
16-Jun-2009 02:44
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"
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);
?>
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
?>
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
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 = strpos($subject, $search);
if($firstChar !== false) {
$beforeStr = substr($subject,0,$firstChar);
$afterStr = substr($subject, $firstChar + strlen($search));
return $beforeStr.$replace.$afterStr;
} else {
return $subject;
}
}
?>
05-Sep-2008 11:15
For PHP 4 < 4.4.5 and PHP 5 < 5.2.1 you may occur (like me) in this bug:
http://www.php-security.org/MOPB/MOPB-39-2007.html
23-Jun-2008 05:18
Yet another deep replace function:
<?php
function str_replace_deep( $search, $replace, $subject)
{
$subject = str_replace( $search, $replace, $subject);
foreach ($subject as &$value)
is_array( $value) and $value =str_replace_deep( $search, $replace, $value);
return $subject;
}
?>
09-Aug-2007 07:22
With PHP 4.3.1, at least, str_replace works fine when working with single arrays but mess it all with two or more dimension arrays.
<?php
$subject = array("You should eat this","this","and this every day.");
$search = "this";
$replace = "that";
$new = str_replace($search, $replace, $subject);
print_r($new); // Array ( [0] => You should eat that [1] => that [2] => and that every day. )
echo "<hr />";
$subject = array(array("first", "You should eat this")
,array("second","this")
,array("third", "and this every day."));
$search = "this";
$replace = "that";
$new = str_replace($search, $replace, $subject);
print_r($new); // Array ( [0] => Array [1] => Array [2] => Array )
?>
05-Jun-2007 06:27
I found that having UTF-8 strings in as argument didnt
work for me using heavyraptors function.
Adding UTF-8 as argument on htmlentities
fixed the problem.
cheers, tim at hysniu.com
<?php
function replace_accents($str) {
$str = htmlentities($str, ENT_COMPAT, "UTF-8");
$str = preg_replace(
'/&([a-zA-Z])(uml|acute|grave|circ|tilde);/',
'$1',$str);
return html_entity_decode($str);
}
?>
26-Feb-2007 01:48
My input is MS Excel file but I want to save ‘,’,“,” as ',',",".
$badchr = array(
"\xc2", // prefix 1
"\x80", // prefix 2
"\x98", // single quote opening
"\x99", // single quote closing
"\x8c", // double quote opening
"\x9d" // double quote closing
);
$goodchr = array('', '', '\'', '\'', '"', '"');
str_replace($badchr, $goodchr, $strFromExcelFile);
Works for me.
16-Feb-2007 08:30
This is a more rigid alternative to spectrereturns at creaturestoke dot com's replace_different function:
<?php
function str_replace_many ($search, $replacements, $subject) {
$index = strlen($subject);
$replacements = array_reverse($replacements);
if (count($replacements) != substr_count($subject, $search)) {
return FALSE;
}
foreach ($replacements as $replacement) {
$index = strrpos(substr($subject, 0, $index), $search);
$prefix = substr($subject, 0, $index);
$suffix = substr($subject, $index + 1);
$subject = $prefix . $replacement . $suffix;
}
return $subject;
}
?>
This will return false if there are a different number of $replacements versus number of occurrences of $search in $subject. Additionally, $search much be exactly one character (if a string is provided, only the first character in the string will be used). Examples:
<?php
echo str_replace_many('?',array('Jane','banana'),'? is eating a ?.');
?>
prints: "Jane is eating a banana."
Before spending hours searching your application why it makes UTF-8 encoding into some malformed something with str_replace, make sure you save your PHP file in UTF-8 (NO BOM).
This was at least one of my problems.
30-Mar-2006 03:40
As an effort to remove those Word copy and paste smart quotes, I've found that this works with UTF8 encoded strings (where $text in the following example is UTF8). Also the elipsis and em and en dashes are replaced.
There is an "invisible" character after the †for the right side double smart quote that doesn't seem to display here. It is chr(157).
<?php
$find[] = '“'; // left side double smart quote
$find[] = 'â€'; // right side double smart quote
$find[] = '‘'; // left side single smart quote
$find[] = '’'; // right side single smart quote
$find[] = '…'; // elipsis
$find[] = '—'; // em dash
$find[] = '–'; // en dash
$replace[] = '"';
$replace[] = '"';
$replace[] = "'";
$replace[] = "'";
$replace[] = "...";
$replace[] = "-";
$replace[] = "-";
$text = str_replace($find, $replace, $text);
?>
25-Aug-2003 01:12
Take care with order when using arrays in replacement.
<?php
$match=array("ONE","TWO","THREE");
$replace=array("TWO WORDS","MANY LETTERS","OTHER IDEAS");
$sample="ONE SAMPLE";
echo str_replace($match,$replace,$sample);
?>
It will show: "MANY LETTERS WORDS SAMPLE"
That is, after replacing "ONE" with "TWO WORDS", process follows with next array item and it changes "TWO" with "MANY LETTERS".
