©
本文檔使用 php中文網手册 發布
(PHP 4, PHP 5)
str_replace — 子字符串替换
$search
, mixed $replace
, mixed $subject
[, int &$count
] )
该函数返回一个字符串或者数组。该字符串或数组是将 subject
中全部的 search
都被 replace
替换之后的结果。
如果没有一些特殊的替换需求(比如正则表达式),你应该使用该函数替换 ereg_replace() 和 preg_replace() 。
如果 search
和 replace
为数组,那么 str_replace() 将对 subject
做二者的映射替换。如果 replace
的值的个数少于 search
的个数,多余的替换将使用空字符串来进行。如果 search
是一个数组而 replace
是一个字符串,那么 search
中每个元素的替换将始终使用这个字符串。该转换不会改变大小写。
如果 search
和 replace
都是数组,它们的值将会被依次处理。
search
查找的目标值,也就是 needle。一个数组可以指定多个目标。
replace
search
的替换值。一个数组可以被用来指定多重替换。
subject
执行替换的数组或者字符串。也就是 haystack。
如果 subject
是一个数组,替换操作将遍历整个 subject
,返回值也将是一个数组。
count
如果被指定,它的值将被设置为替换发生的次数。
该函数返回替换后的数组或者字符串。
Example #1 str_replace() 基本范例
<?php
// 赋值: <body text='black'>
$bodytag = str_replace ( "%body%" , "black" , "<body text='%body%'>" );
// 赋值: Hll Wrld f PHP
$vowels = array( "a" , "e" , "i" , "o" , "u" , "A" , "E" , "I" , "O" , "U" );
$onlyconsonants = str_replace ( $vowels , "" , "Hello World of PHP" );
// 赋值: 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 );
// 赋值: 2
$str = str_replace ( "ll" , "" , "good golly miss molly!" , $count );
echo $count ;
?>
Example #2 可能的 str_replace() 替换范例
<?php
// 替换顺序
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n" ;
$order = array( "\r\n" , "\n" , "\r" );
$replace = '<br />' ;
// 首先替换 \r\n 字符,因此它们不会被两次转换
$newstr = str_replace ( $order , $replace , $str );
// 输出 F ,因为 A 被 B 替换,B 又被 C 替换,以此类推...
// 由于从左到右依次替换,最终 E 被 F 替换
$search = array( 'A' , 'B' , 'C' , 'D' , 'E' );
$replace = array( 'B' , 'C' , 'D' , 'E' , 'F' );
$subject = 'A' ;
echo str_replace ( $search , $replace , $subject );
// 输出: apearpearle pear
// 由于上面提到的原因
$letters = array( 'a' , 'p' );
$fruit = array( 'apple' , 'pear' );
$text = 'a p' ;
$output = str_replace ( $letters , $fruit , $text );
echo $output ;
?>
Note: 此函数可安全用于二进制对象。
由于 str_replace() 的替换时从左到右依次进行的,进行多重替换的时候可能会替换掉之前插入的值。参见该文档的范例。
Note:
该函数区分大小写。使用 str_ireplace() 可以进行不区分大小写的替换。
[#1] mrrehbein at gmail dot com [2015-04-03 13:25:26]
nikolaz dot tang at hotmail dot com's solution of using json_encode/decode is interesting, but a couple of issues to be aware of with it.
<?php
// From: nikolaz dot tang at hotmail dot com's post
function str_replace_json($search, $replace, $subject){
return json_decode(str_replace($search, $replace, json_encode($subject)));
}
?>
json_decode will return objects, where arrays are probably expected. This is easily remedied by adding 2nd parameter 'true' to json_decode.
$search and $replace could contain strings that match json encoding, which will either change the structure returned by this method, or break the json.
ie:
<?php
var_dump(str_replace_json('":"', '","', ['this' => 'stuff']));
var_dump(str_replace_json('this":"', 'this" : "thing", "with":"', ['this' => 'stuff']));
?>
[#2] borasahin at gmail dot com [2015-03-02 08:59:37]
jSON Turkish Characters Problem - (PHP < 5.4 for example)
<?php
function json_decode_tr($json){
$json_char = array("u00e7","u0131","u00fc","u011f","u00f6","u015f","u0130","u011e","u00dc","u00d6","u015e","u00c7");
$turkish = array("?","?","??","?","?","?","?","?","?","?","?","?");
$result = str_replace($json_char, $turkish, $json);
return json_decode($json);
}
?>
[#3] karst at onlinq dot nl [2014-10-17 13:57:04]
"If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though. "
I think one important (and not at all vaguely theoretical) use-case is completely ignored here. Take, for example, the way the PDO handles parameter replacement.
If we have the following query:
"SELECT * FROM my_table WHERE (id = ? AND my_column = ? AND other_column = ?);"
The "?"s should be replaced by each successive variable in a $parameters array. That is EXACTLY the use case for "search" being a value and "replace" being an array.
Considering that this is not only a real-world example but also part of a core PHP functionality I find it very strange that it's dismissed so easily here.
[#4] Ing. Mirko Plazotta [2014-09-04 09:27:16]
<?php
// a very beatiful way to do multiple replacements is this one, using just one array
$replaceThis = Array(
'old word' => 'new word',
'was' => 'it',
'past' => 'future',
);
$originalText = "every old word was a thing of the past...";
$replacedText = str_replace(array_keys($replaceThis), $replaceThis, $originalText);
echo $replacedText;
?>
[#5] markem at sim1 dot us [2014-08-27 20:04:32]
I was working with MySQL and displaying the title to things on the web page. I'd written a script to ensure single and double quotes were removed from the title. I used
$title = str_replace( "'", "", $title );
and
$title = str_replace( '"', "", $title );
But still the single and double quotes continued. So I wrote a bit of code to print out each character separated by a dash. Like so:
for( $i=0; $i<strlen($title); $i++ ){
echo "$i-";
}
echo "<br>\n";
This displayed:
m-y-c-o-m-p-a-n-y- b-b-&-#-3-9-;-s
Which made me go "Oh! I get it."
The MySQL function real_escape_string modifies the single quotes to be ' and double quotes as " These still show up as single and double quotes under HTML and most importantly -
JAVASCRIPT sees the " and ' as actual single or double
quotes. So if you are passing arguments to a function you have
to get rid of them or else you will get an error on trying to call
a given function. Example:
<a href="javascript:func1('mycompany bbs's")'">
becomes
<a href="javascript:func1('mycompany bbs's');">
Which then will give you an error because there is a single quote inside of the single quoted string. HOWEVER, the
$title = str_replace( "'", "", $title );
WILL NOT FIND a single quote. Instead, you have to do this:
$title = str_replace( "'", "'", $title );
and
$title = str_relace( """, '"', $title );
(Or you could just get rid of them.)
So remember! If you are trying to remove single and double quotes and are using MySQL and MySQL's real_escape_string() function that you might be having single and double quotes hanging around which are defined as ' and " but which show up as single and double quotes as well as causing problems in your Javascripts.
[#6] abc dot abc1 at vp dot pl [2014-02-18 08:59:21]
I have:
<?php
';
function lacz_bd()
{
$db = new mysqli('localhost', '_admin', 'pass', 'db');
if (! $db)
return false;
$db->autocommit(TRUE);
return $db;
}
// dane do ramy pliku .xml
$kanalRSS = '<?xml version="1.0" encoding="ISO-8859-2"?>
$kanalRSS .= '<trovit>';
$kanalRSS .= '<ad>';
// po?aczenie z baz? danych
$db = lacz_bd();
//zapytanie okre?laj?ce dane ktore powinny byc pobrane z tabeli
// teraz pobierzmy wszystkie dane spelniajace warunek category_id=140
$zapytanie = "SELECT * FROM announcements WHERE category_id in (140,141,142,143,144)";
$wynik = $db->query($zapytanie);
$ile_znalezionych = $wynik->num_rows;
for ($i=0; $i <$ile_znalezionych; $i++)
{
$wiersz = $wynik->fetch_assoc();
//usuwamy znaczniki html ze wszystkich danych z tabeli, polskie znaki, duze litery
$string_title = $wiersz['annoucement_title'];
$string_url = $wiersz['annoucement_title'];
$pattern = array(' ', ',', '.', '/?/', '/?/', '/?/', '/?/', '/?/', '/?/', '/?/', '/?/' ,'/??/', '/?/', '/??/', '/?/', '/?/', '/?/', '/?/', '/?/', '/?/', '/?/',);
$replacement = array('-', '', '', 'a', 'A', 'c', 'C', 'e', 'E', 'l', 'L', 'n', 'N', 'o', 'O', 's', 'S', 'z', 'Z', 'z', 'Z',);
$string_url = strtolower(str_replace($pattern, $replacement, $string_url));
$wiersz['annoucement_content'] = strip_tags($wiersz['annoucement_content']);
//dodajemy nazwy rodzajow ogloszenia
$string_type = $wiersz['annoucement_type'];
$_type = array('1', '2', '3', '4');
$_new_type = array('Buy', 'Replace', 'For Rent', 'For Sale');
$wiersz['annoucement_type'] = str_replace($_type, $_new_type, $string_type);
//tutaj generujemy zawartosc pliku .xml, ktora pobierana jest z tabeli announcements
$kanalRSS .= '<item>';
$kanalRSS .= '<id><![CDATA['.$wiersz['annoucement_id'].']]></id>';
$kanalRSS .= '<url><![CDATA[http://oglaszajtu.pl/ogloszenia/'.$wiersz['annoucement_id'].'/'.$string_url.']]></url>';
$kanalRSS .= '<title><![CDATA['.$string_title.']]></title>';
$kanalRSS .= '<type><![CDATA['.$wiersz['annoucement_type'].']]></type>';
$kanalRSS .= '<content><![CDATA['.$wiersz['annoucement_content'].']]></content>';
$kanalRSS .= '<date><![CDATA['.$wiersz['annoucement_date_added'].']]></date>';
$kanalRSS .= '</item>';
}
$kanalRSS .= ' </ad>';
$kanalRSS .= '</trovit>';
//Zapisujemy wygenerowany kod XML do pliku moj_rss.xml
$fp = fopen('trovit_oglaszajtu.xml','w');
fwrite($fp,$kanalRSS);
fclose($fp);
?>
And one problem - ?,??,?, etc - don't delete
oglaszajtu.pl/moj_rss.php
oglaszajtu.pl/trovit_oglaszajtu.xml
:-(
Can anyone help me?
Thx
rel
[#7] Anonymous [2013-07-19 10:01:10]
@moostende at gmail dot com
If you want to remove all dashes but one from the string '-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you CAN use str_replace !
<?php
function foo($str)
{
do {
$str = str_replace("--", "-", $str, $count);
} while ($count > 0);
return $str;
}
echo foo("-aaa----b-c-----d--e---f");
?>
This outputs the following:
-aaa-b-c-d-e-f
[#8] cmbecker69 at gmx dot de [2013-06-17 01:53:35]
To collapse multiple consecutive space characters to a single one, don't use str_replace() inside a loop--use preg_replace() instead for clarity and better performance:
<?php
$str = ' This is a test ';
$str = preg_replace('/ +/', ' ', $str);
?>
[#9] kriscraig at php dot net [2012-07-20 23:03:32]
<?php
public static function convert_chars_to_entities( $str )
{
$str = str_replace( '?', 'À', $str );
$str = str_replace( '?', 'Á', $str );
$str = str_replace( '?', 'Â', $str );
$str = str_replace( '?', 'Ã', $str );
$str = str_replace( '?', 'Ä', $str );
$str = str_replace( '?', 'Å', $str );
$str = str_replace( '?', 'Æ', $str );
$str = str_replace( '?', 'Ç', $str );
$str = str_replace( '?', 'È', $str );
$str = str_replace( '?', 'É', $str );
$str = str_replace( '?', 'Ê', $str );
$str = str_replace( '?', 'Ë', $str );
$str = str_replace( '?', 'Ì', $str );
$str = str_replace( '?', 'Í', $str );
$str = str_replace( '?', 'Î', $str );
$str = str_replace( '?', 'Ï', $str );
$str = str_replace( '?', 'Ð', $str );
$str = str_replace( '?', 'Ñ', $str );
$str = str_replace( '?', 'Ò', $str );
$str = str_replace( '?', 'Ó', $str );
$str = str_replace( '?', 'Ô', $str );
$str = str_replace( '?', 'Õ', $str );
$str = str_replace( '?', 'Ö', $str );
$str = str_replace( '??', '×', $str ); // Yeah, I know. But otherwise the gap is confusing. --Kris
$str = str_replace( '?', 'Ø', $str );
$str = str_replace( '?', 'Ù', $str );
$str = str_replace( '?', 'Ú', $str );
$str = str_replace( '?', 'Û', $str );
$str = str_replace( '?', 'Ü', $str );
$str = str_replace( '?', 'Ý', $str );
$str = str_replace( '?', 'Þ', $str );
$str = str_replace( '?', 'ß', $str );
$str = str_replace( '??', 'à', $str );
$str = str_replace( '??', 'á', $str );
$str = str_replace( '?', 'â', $str );
$str = str_replace( '?', 'ã', $str );
$str = str_replace( '?', 'ä', $str );
$str = str_replace( '?', 'å', $str );
$str = str_replace( '?', 'æ', $str );
$str = str_replace( '?', 'ç', $str );
$str = str_replace( '??', 'è', $str );
$str = str_replace( '??', 'é', $str );
$str = str_replace( '??', 'ê', $str );
$str = str_replace( '?', 'ë', $str );
$str = str_replace( '??', 'ì', $str );
$str = str_replace( '??', 'í', $str );
$str = str_replace( '?', 'î', $str );
$str = str_replace( '?', 'ï', $str );
$str = str_replace( '?', 'ð', $str );
$str = str_replace( '?', 'ñ', $str );
$str = str_replace( '??', 'ò', $str );
$str = str_replace( '??', 'ó', $str );
$str = str_replace( '?', 'ô', $str );
$str = str_replace( '?', 'õ', $str );
$str = str_replace( '?', 'ö', $str );
$str = str_replace( '??', '÷', $str ); // Yeah, I know. But otherwise the gap is confusing. --Kris
$str = str_replace( '?', 'ø', $str );
$str = str_replace( '??', 'ù', $str );
$str = str_replace( '??', 'ú', $str );
$str = str_replace( '?', 'û', $str );
$str = str_replace( '??', 'ü', $str );
$str = str_replace( '?', 'ý', $str );
$str = str_replace( '?', 'þ', $str );
$str = str_replace( '?', 'ÿ', $str );
return $str;
}
?>
[#10] bfrohs at gmail dot com [2012-07-10 18:27:33]
This function implements $limit for str_replace(); is 100% backward compatible with str_replace(); uses str_replace() whenever possible (for performance reasons); supports arrays for $search, $replace, and $subject; and is fully commented.
<?php
function str_replace_limit($search, $replace, $subject, &$count, $limit = -1){
$count = 0;
// Invalid $limit provided
if(!($limit===strval(intval(strval($limit))))){
trigger_error('Invalid $limit `'.$limit.'` provided. Expecting an '.
'integer', E_USER_WARNING);
return $subject;
}
// Invalid $limit provided
if($limit<-1){
trigger_error('Invalid $limit `'.$limit.'` provided. Expecting -1 or '.
'a positive integer', E_USER_WARNING);
return $subject;
}
// No replacements necessary
if($limit===0){
trigger_error('Invalid $limit `'.$limit.'` provided. Expecting -1 or '.
'a positive integer', E_USER_NOTICE);
return $subject;
}
// Use str_replace() when possible
if($limit===-1){
return str_replace($search, $replace, $subject, $count);
}
if(is_array($subject)){
// Loop through $subject values
foreach($subject as $key => $this_subject){
// Skip values that are arrays
if(!is_array($this_subject)){
// Call this function again
$this_function = __FUNCTION__;
$subject[$key] = $this_function($search, $replace, $this_subject, $this_count, $limit);
// Adjust $count
$count += $this_count;
// Adjust $limit
if($limit!=-1){
$limit -= $this_count;
}
// Reached $limit
if($limit===0){
return $subject;
}
}
}
return $subject;
} elseif(is_array($search)){
// Clear keys of $search
$search = array_values($search);
// Clear keys of $replace
if(is_array($replace)){
$replace = array_values($replace);
}
// Loop through $search
foreach($search as $key => $this_search){
// Don't support multi-dimensional arrays
$this_search = strval($this_search);
// If $replace is an array, use $replace[$key] if exists, else ''
if(is_array($replace)){
if(array_key_exists($key, $replace)){
$this_replace = strval($replace[$key]);
} else {
$this_replace = '';
}
} else {
$this_replace = strval($replace);
}
// Call this function again for
$this_function = __FUNCTION__;
$subject = $this_function($this_search, $this_replace, $subject, $this_count, $limit);
// Adjust $count
$count += $this_count;
// Adjust $limit
if($limit!=-1){
$limit -= $this_count;
}
// Reached $limit
if($limit===0){
return $subject;
}
}
return $subject;
} else {
$search = strval($search);
$replace = strval($replace);
// Get position of first $search
$pos = strpos($subject, $search);
// Return $subject if $search cannot be found
if($pos===false){
return $subject;
}
// Get length of $search
$search_len = strlen($search);
// Loop until $search cannot be found or $limit is reached
for($i=0;(($i<$limit)||($limit===-1));$i++){
$subject = substr_replace($subject, $replace, $pos, $search_len);
// Increase $count
$count++;
// Get location of next $search
$pos = strpos($subject, $search);
// Break out of loop
if($pos===false){
break;
}
}
return $subject;
}
}
?>
[#11] christof dot rieger at r-tron dot de [2012-04-25 20:41:56]
In many countries the numeric format is 1.000,33 in english it is 1,000.33
This function converts numeric arguments always into the PHP confirm numeric format. If only one seperator is into the numericstring so it is interpreted as the decimalpoint.
function dp($zahl)
{
if ((strpos($zahl,".") > "-1") | (strpos($zahl,",") > "-1")) {
if ((strpos($zahl,".") > "-1") & (strpos($zahl,",") > "-1")) {
if (strpos($zahl,".") > strpos($zahl,",")){
return str_replace(",","",$zahl);
} else {
return str_replace(",",".",str_replace(".","",$zahl));
}
} else {
if (strpos($zahl,".") > "-1") {
if (strpos($zahl,".") == strrpos($zahl,".")) {
return $zahl;
} else {
return str_replace(".","",$zahl);
}
} else {
if (strpos($zahl,",") == strrpos($zahl,",")) {
return str_replace(",",".",$zahl);
} else {
return str_replace(",","",$zahl);
}
} }
} else {
return $zahl;
} }
[#12] Denzel Morris [2012-04-06 14:43:11]
Maybe obvious to veteran PHP programmers but less so to novice PHP programmers is the fact that this is invalid:
<?php
str_replace($search, $replace, $subject, 1);
?>
At a glance it appears to be a reasonable request, until you realize that the fourth parameter must be a variable in order to be passed as a reference. A replacement:
<?php
str_replace($search, $replace, $subject, $temp = 1);
// or
$temp = 1;
str_replace($search, $replace, $subject, $temp);
?>
[#13] cc at cc dot com [2012-03-31 05:26:07]
I found a pretty low tech solution to avoid the "gotcha" without worrying about the array order of how things are replaced. I could not "order" the replacement array easily because it was being read from a database table.
Anyway if you add an identifiable token to each replaced word, then just filter this out at the very end, no nested search terms are found. I just dynamically add the %% after the first char of each word before pumping it into the str_ireplace function.
$find = array("as1", "as2", "as3", "flex");
$replace = array("<a href = \"#as1\">A%%uto S%%entry R%%ev. A%%</a>", "<a href = \"#as2\">A%%uto S%%entry E%%xp</a>", "<a href = \"#as3\">A%%uto S%%entry f%%lex</a>", "<a style = \"color: red;\" href = \"#flex\">f%%lex</a>");
$text = str_ireplace($find, $replace, $text);
echo str_ireplace("%%", "", $text);
In this case I am using %% as my token as this is an unlikely char combo for me.
[#14] moostende at gmail dot com [2011-09-26 23:20:01]
Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row.
If you want to remove all dashes but one from the string '-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you cannot use str_replace. Instead, use preg_replace:
<?php
$challenge = '-aaa----b-c-----d--e---f';
echo str_replace('--', '-', $challenge).'<br>';
echo preg_replace('/--+/', '-', $challenge).'<br>';
?>
This outputs the following:
-aaa--b-c---d-e--f
-aaa-b-c-d-e-f
[#15] mbullard at accuvista dot co dot uk [2011-07-14 02:42:18]
Insert space after comma.
If you have a form that stores results in a database field as comma separated values, when you display this data you can use the following to insert a space after each comma:
<?php
$find[] = ',';
$replace[] = ', ';
$text = str_replace($find, $replace, $row_rsRecordset['Field']);
print_r($text);
?>
Notes:
1) To get round the Replacement Order Gotcha, the comma is also replaced with its code equivalent: ,
2) You can adapt the $replace section to suit your needs: swap out the code with <br/> or replace comma and space with · etc.
[#16] hakre [2011-07-06 08:08:31]
I was looking for a str_replace function supporting callbacks. As I didn't found one I wrote one my own. Works exactly like str_replace, but the replace parameter is a callback or an array of callbacks (instead of string/strings in str_replace). The callback function accepts two arguments, the string that is being replaced and the count of the replacement being done.
<?php
function str_ureplace($search, $replace, $subject, &$replace_count = null) {
$replace_count = 0;
// validate input
$search = array_values((array) $search);
$searchCount = count($search);
if (!$searchCount) {
return $subject;
}
foreach($search as &$v) {
$v = (string) $v;
}
unset($v);
$replaceSingle = is_callable($replace);
$replace = $replaceSingle ? array($replace) : array_values((array) $replace);
foreach($replace as $index=>$callback) {
if (!is_callable($callback)) {
throw new Exception(sprintf('Unable to use %s (#%d) as a callback', gettype($callback), $index));
}
}
// search and replace
$subjectIsString = is_string($subject);
$subject = (array) $subject;
foreach($subject as &$haystack) {
if (!is_string($haystack)) continue;
foreach($search as $key => $needle) {
if (!$len = strlen($needle))
continue;
$replaceSingle && $key = 0;
$pos = 0;
while(false !== $pos = strpos($haystack, $needle, $pos)) {
$replaceWith = isset($replace[$key]) ? call_user_func($replace[$key], $needle, ++$replace_count) : '';
$haystack = substr_replace($haystack, $replaceWith, $pos, $len);
}
}
}
unset($haystack);
return $subjectIsString ? reset($subject) : $subject;
}
?>
[#17] jay_knows_(all)uk at hotmail dot com [2011-02-16 07:16:34]
This strips out horrible MS word characters.
Just keep fine tuning it until you get what you need, you'll see ive commented some out which caused problems for me.
There could be some that need adding in, but its a start to anyone who wishes to make their own custom function.
<?php
function msword_conversion($str)
{
$str = str_replace(chr(130), ',', $str); // baseline single quote
$str = str_replace(chr(131), 'NLG', $str); // florin
$str = str_replace(chr(132), '"', $str); // baseline double quote
$str = str_replace(chr(133), '...', $str); // ellipsis
$str = str_replace(chr(134), '**', $str); // dagger (a second footnote)
$str = str_replace(chr(135), '***', $str); // double dagger (a third footnote)
$str = str_replace(chr(136), '^', $str); // circumflex accent
$str = str_replace(chr(137), 'o/oo', $str); // permile
$str = str_replace(chr(138), 'Sh', $str); // S Hacek
$str = str_replace(chr(139), '<', $str); // left single guillemet
// $str = str_replace(chr(140), 'OE', $str); // OE ligature
$str = str_replace(chr(145), "'", $str); // left single quote
$str = str_replace(chr(146), "'", $str); // right single quote
// $str = str_replace(chr(147), '"', $str); // left double quote
// $str = str_replace(chr(148), '"', $str); // right double quote
$str = str_replace(chr(149), '-', $str); // bullet
$str = str_replace(chr(150), '-?C', $str); // endash
$str = str_replace(chr(151), '--', $str); // emdash
// $str = str_replace(chr(152), '~', $str); // tilde accent
// $str = str_replace(chr(153), '(TM)', $str); // trademark ligature
$str = str_replace(chr(154), 'sh', $str); // s Hacek
$str = str_replace(chr(155), '>', $str); // right single guillemet
// $str = str_replace(chr(156), 'oe', $str); // oe ligature
$str = str_replace(chr(159), 'Y', $str); // Y Dieresis
$str = str_replace('??C', '°C', $str); // Celcius is used quite a lot so it makes sense to add this in
$str = str_replace('?', '£', $str);
$str = str_replace("'", "'", $str);
$str = str_replace('"', '"', $str);
$str = str_replace('?C', '–', $str);
return $str;
}
?>
[#18] mevdschee [2011-01-29 03:19:46]
say you want every "a" replaced by "abba" and every "b" replaced by "baab" in the string "ab" you do:
<?php
$search = array("a","b");
$replace = array("abba","baab");
echo str_replace($search,$replace,"ab");
?>
that results in "abaabbaababaab" and not the expected "abbabaab"
I wrote this little snippet to solve the replacements-in-replacement problem:
<?php
function search_replace($s,$r,$sql)
{ $e = '/('.implode('|',array_map('preg_quote', $s)).')/';
$r = array_combine($s,$r);
return preg_replace_callback($e, function($v) use ($s,$r) { return $r[$v[1]]; },$sql);
}
echo search_replace($search,$replace,"ab");
?>
that results in the expected "abbabaab"
[#19] nikolaz dot tang at hotmail dot com [2010-11-11 20:57:04]
A faster way to replace the strings in multidimensional array is to json_encode() it, do the str_replace() and then json_decode() it, like this:
<?php
function str_replace_json($search, $replace, $subject){
return json_decode(str_replace($search, $replace, json_encode($subject)));
}
?>
This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding.
Compared to:
<?php
function str_replace_deep($search, $replace, $subject)
{
if (is_array($subject))
{
foreach($subject as &$oneSubject)
$oneSubject = str_replace_deep($search, $replace, $oneSubject);
unset($oneSubject);
return $subject;
} else {
return str_replace($search, $replace, $subject);
}
}
?>
[#20] apmuthu at usa dot net [2010-06-19 12:31:34]
If we have a html template that contains placeholders in curly braces that need to be replaced in runtime, the following function will do it using str_replace:
<?php
function parse_template($filename, $data) {
// example template variables {a} and {bc}
// example $data array
// $data = Array("a" => 'one', "bc" => 'two');
$q = file_get_contents($filename);
foreach ($data as $key => $value) {
$q = str_replace('{'.$key.'}', $value, $q);
}
return $q;
}
?>
[#21] cableray [2010-06-11 00:03:09]
If you wish to get around the 'gotcha', you could do something like this:
<?php
$find=array('a', 'p', '^', '*');
$replace = array('^', '*', 'apple', 'pear');
str_replace($find, $replace, 'a p');
?>
The idea here is that you first replace the items you want with unique identifiers (that you are unlikely to find in the subject) and then search for those identifiers and then replace them.
[#22] christian dot reinecke at web dot de [2010-05-14 12:06:28]
If you need to replace a string in another, but only once but still in all possible combinations (f.e. to replace "a" with "x" in "aba" to get array("xba", "abx")) you can use this function:
<?php
function getSingleReplaceCombinations($replace, $with, $inHaystack)
{
$splits = explode($replace, $inHaystack);
$result = array();
for ($i = 1, $ix = count($splits); $i < $ix; ++$i) {
$previous = array_slice($splits, 0, $i);
$next = array_slice($splits, $i);
$combine = array_pop($previous) . $with . array_shift($next);
$result[] = implode($replace, array_merge($previous, array($combine), $next));
}
return $result;
}
var_dump(getSingleReplaceCombinations("a", "x", "aba")); // result as mentioned above
?>
It may not be the best in performance, but it works.
[#23] jbarnett at jmbelite dot com [2010-04-26 13:23:22]
Might be worth mentioning that a SIMPLE way to accomplish Example 2 (potential gotchas) is to simply start your "replacements" in reverse.
So instead of starting from "A" and ending with "E":
<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
// replaces A to B, B to C, C to D, D to E, E to F (makes them all F)
// start from "E" and end with "A":
$search = array('E', 'D', 'C', 'B', 'A');
$replace = array('F', 'E', 'D', 'C', 'B');
// replaces E to F, D to E, C to D, B to C, A to B (prevents from
// multiple replacements of already replaced values)
?>
So basically start from the "end" and put the replacements in an order where the "replaced value" won't equal a value that exists later in the "search array".
[#24] pjcdawkins at googlemail dot com [2010-04-23 17:23:15]
Here's a deep replace function allowing multi-dimensional arrays in $search, $replace and $subject. The keys and other structure of $subject are preserved.
<?php
// Auxiliary function:
function _replaceWithAnything($search,$replace,$subject){
if(!is_array($search) || !is_array($replace)){
$search=array($search);
$replace=array($replace);
}
$match=array_search($subject,$search,true);
if($match!==false && array_key_exists($match,$replace))
$subject=$replace[$match];
return $subject;
}
// Main function:
function deepReplace($search,$replace,$subject){
if(!is_array($subject))
return _replaceWithAnything($search,$replace,$subject);
foreach($subject as &$val){
if(is_array($val)){
$val=deepReplace($search,$replace,$val);
continue;
}
$val=_replaceWithAnything($search,$replace,$val);
}
return $subject;
}
?>
[#25] fleshgrinder at gmx dot at [2010-04-16 05:50:56]
Fast function to replace new lines from a given string. This is interesting to replace all new lines from e. g. a text formatted in HTML retrieved from database and printing it without the unnecessary new lines. This results in slightly faster rendering in the Web browser.
<?php
function replace_newline($string) {
return (string)str_replace(array("\r", "\r\n", "\n"), '', $string);
}
?>
[#26] Wes Foster [2009-12-17 13:32:02]
Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array.
For example:
<?php
$replace = array(
'dog' => 'cat',
'apple' => 'orange'
'chevy' => 'ford'
);
$string = 'I like to eat an apple with my dog in my chevy';
echo str_replace_assoc($replace,$string);
// Echo: I like to eat an orange with my cat in my ford
?>
Here is the function:
<?php
function strReplaceAssoc(array $replace, $subject) {
return str_replace(array_keys($replace), array_values($replace), $subject);
}
?>
[Jun 1st, 2010 - EDIT BY thiago AT php DOT net: Function has been replaced with an updated version sent by ljelinek AT gmail DOT com]
[#27] Decko [2009-10-15 01:41:18]
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 == '/'
?>
[#28] Alberto Lepe [2009-06-15 19:44:50]
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"
[#29] moz667 at gmail dot com [2009-05-21 09:49:55]
<?php
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);
?>
[#30] michael dot moussa at gmail dot com [2009-01-29 06:38:46]
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
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!
?>
<?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
?>
[#31] nospam at nospam dot com [2008-12-02 14:55:48]
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'));
// 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
[#32] nick at NOSPAM dot pitchinteractive dot com [2008-10-06 16:12:18]
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;
}
}
?>
[#33] paolo A T doppioclick D O T com [2008-09-05 04:15:56]
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
[#34] troy at troyonline dot com [2008-06-22 22:18:01]
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;
}
?>
[#35] David Gimeno i Ayuso (info at sima dot cat) [2007-08-09 12:22:53]
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 )
?>
[#36] kole [2007-02-25 17:48:56]
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.
[#37] [2007-01-15 01:42:02]
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.
[#38] matt wheaton [2006-03-30 07:40:39]
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);
?>