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]
str_replace
(PHP 4, PHP 5)
str_replace — Replace all occurrences of the search string with the replacement string
Description
This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.
If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().
Parameters
If search and replace are arrays, then str_replace() takes a value from each array and uses them to do search and replace on subject . If replace has fewer values than search , then an empty string is used for the rest of replacement values. 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.
If search or replace are arrays, their elements are processed first to last.
- search
-
- replace
-
- subject
-
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
-
Note: If passed, this will hold the number of matched and replaced needles.
Return Values
This function returns a string or an array with the replaced values.
Changelog
| Version | Description |
|---|---|
| 5.0.0 | The count parameter was added. |
| 4.3.3 | The behaviour of this function changed. In older versions a bug existed when using arrays as both search and replace parameters which caused empty search indexes to be skipped without advancing the internal pointer on the replace array. This has been corrected in PHP 4.3.3, any scripts which relied on this bug should remove empty search values prior to calling this function in order to mimic the original behavior. |
| 4.0.5 | Most parameters can now be an array. |
Examples
Example #1 str_replace() examples
<?php
// Provides: <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
// Provides: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
// Provides: 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);
// Use of the count parameter is available as of PHP 5.0.0
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count; // 2
// Order of replacement
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order = array("\r\n", "\n", "\r");
$replace = '<br />';
// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, $replace, $str);
// Outputs: apearpearle pear
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;
?>
Notes
Note: This function is binary-safe.
Note: This function is case-sensitive. Use str_ireplace() for case-insensitive replace.
str_replace
07-Dec-2008 01:48
07-Dec-2008 04: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 11: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
30-Oct-2008 12: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 08: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 07: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;
}
?>
07-Oct-2008 01: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;
}
}
?>
25-Sep-2008 04:19
Changing English number with Persian number
<?php
function farsi_number($input)
{
$englishNumber=
array("0","1","2","3","4","5","6","7","8","9");
$persianNumber=
array("۰","۱","۲","۳","۴","۵","۶","۷","۸","۹");
return str_replace($englishNumber,
$persianNumber, $input);
}
?>
05-Sep-2008 01: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
29-Aug-2008 08:54
If you need to replace áóíóú and other special char, you need encondig type suport.
For this, just use htmlentities and some regular expressions
<?PHP
function RemoveAcentos($str, $enc = "UTF-8"){
$acentos = array(
'A' => '/À|Á|Â|Ã|Ä|Å/',
'a' => '/à|á|â|ã|ä|å/',
'C' => '/Ç/',
'c' => '/ç/',
'E' => '/È|É|Ê|Ë/',
'e' => '/è|é|ê|ë/',
'I' => '/Ì|Í|Î|Ï/',
'i' => '/ì|í|î|ï/',
'N' => '/Ñ/',
'n' => '/ñ/',
'O' => '/Ò|Ó|Ô|Õ|Ö/',
'o' => '/ò|ó|ô|õ|ö/',
'U' => '/Ù|Ú|Û|Ü/',
'u' => '/ù|ú|û|ü/',
'Y' => '/Ý/',
'y' => '/ý|ÿ/',
'a.' => '/ª/',
'o.' => '/º/'
);
return preg_replace($acentos, array_keys($acentos), htmlentities($str,ENT_NOQUOTES, $enc));
}
?>
06-Aug-2008 10:13
I'm sorry. I can't believe it: I messed up again. Something that I forgot is that the php empty() function considers the number zero (0) as an empty value. Therefore, we need to change our if statement to the following:
<?php
if ($i[0] !== null) $subject .= $replace[$i[0]];
?>
If we left it how it was, the replace ignores the first element of the arrays. ($array[0])
The reason that I used !empty() before, is that I wasn't sure what array_keys() returns if the element is not found (null? and empty string?), since both null and the empty string print out the same and I couldn't find what it returned in this case, in the manual.
The final, working function would look like:
<?php
function str_replace_once($search, $replace, $subject) {
$newArr = str_split($subject);
$subject = '';
foreach ($newArr as $nchar)
{
$i = array_keys($search, $nchar);
if ($i[0] !== null) $subject .= $replace[$i[0]];
else $subject .= $nchar;
}
return $subject;
}
?>
06-Aug-2008 09:28
Sorry, folks. That last note I put up won't work quite correctly. Unlike str_replace(), that snippet I showed you will replace any characters that aren't in your $search array with an empty string.
To correct this behavior, add this check to the foreach loop:
<?php
//...
if (!empty($i[0])) $subject .= $replace[$i[0]];
else $subject .= $nchar; //now, if the search character isn't found (ie, we don't care about it), it will stay the same, instead of getting replaced by an empty string.
?>
The whole thing would look like the following, if you were to put it into a function:
<?php
function char_replace_once($search, $replace, $subject) {
$newArr = str_split($subject);
$subject = '';
foreach ($newArr as $nchar)
{
$i = array_keys($search, $nchar);
if (!empty($i[0])) $subject .= $replace[$i[0]];
else $subject .= $nchar;
}
return $subject;
}
?>
I'm sure it may not be as efficient as str_replace(), but it successfully replaces characters, correctly.
ONE OTHER IMPORTANT THING TO NOTE: Unlike I said before, this will only work for character replacement - not string replacement. The reason, of course, is that the original string gets split into an array, who's members are only one character. Sorry about that.
That drawback aside, though, this is still a useful function for doing complete, accurate character replacement.
06-Aug-2008 08:29
Note that the str_replace() function is recursive. This is not usually a problem, unless you are trying to do a replace in which a character or string occurs in the $search array, after the same character or string occurs in the $replace array. (For instance, imagine doing a global character replace.)
To demonstrate, take a look at the folowing:
<?php
$search = array('q','w','e','r','t','y','u');
$replace = array('z','s','d','e','y','f','g');
$mystring = 'qwertyu';
//Outputs: zsdeffg
echo str_replace($search, $replace, $mystring);
?>
As you would expect, the q gets replaced by a z, the w by an s, and so on. Everything is correct, except that the t doesn't seem to have been replaced by a y. This is not entirely true, however. What happened is that it did, indeed get replaced by a y, but then on the next pass of the str_replace() function, str_replace() found a y and replaced it with an f.
To get this to work as we'd like (every letter in the $search array replaced by the cooresponding spot in the $replace array), we can do something like the following:
<?php
$search = array('q','w','e','r','t','y','u');
$replace = array('z','s','d','e','y','f','g');
$mystring = 'qwertyu';
//Outputs: zsdeffg (Not what we wanted.)
echo str_replace($search, $replace, $mystring);
$newArr = str_split($mystring); //split $mystring into an array of characters. For php4, you'll have to create the str_split() function.
$newstring = '';
foreach ($newArr as $nchar)
{
$i = array_keys($replace, $nchar); //get the key(s) in the $search array for the character we're replacing. (we assume it occurs only once.) Returns an array of length, 1.
$newstring .= $replace[$i[0]]; //find the character in the $replace array that matches the position of the one we're replacing, and add it to $newstring.
}
//Outputs: zsdeyfg
echo $newstring;
?>
This time, as you can see, there is a y in place of the t, which was what we wanted. :)
Hope that clears up any confusion for anyone wondering why their strings aren't getting replaced as they'd expect.
23-Jun-2008 07: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;
}
?>
20-Jun-2008 01:52
On the 19th of June, 2008, max at bitsonnet dot com posted a function interpolate that used create_function. I'd never seen create_function before and I thought it was very educational. Thanks, Maxim!
However, the interpolate function can be improved, speed-wise:
<?php
function interpolate2($template, $hash, $prefix = '#{', $postfix = '}')
{
$tmp = array();
foreach($hash as $k => $v)
{
$tmp[$prefix . $k . $postfix] = $v;
}
return str_replace(array_keys($tmp), array_values($tmp), $template);
}
echo interpolate2('Hello, #{username}. Welcome to #{site}.', array('username' => 'World', 'site' => 'php.net'));
?>
According to my own tests, this version is somewhere between 4 and 5 times faster.
Note, btw, that I used a very similar function on the sprintf page.
19-Jun-2008 11:00
I always miss interpolate functionality in PHP, so I wrote this little helper method. It allows you to specify your own markup using $prefix and $postfix.
<?php
# Interpolate a string using hash.
# by Maxim Chernyak ( http://mediumexposure.com )
function interpolate($template, $hash, $prefix = '#{', $postfix = '}' ) {
$tokenize = create_function('$token', 'return "'. $prefix .'".$token."'.$postfix.'";');
$keys = array_keys($hash);
$values = array_values($hash);
$keys = array_map($tokenize, $keys);
return str_replace($keys, $values, $template);
}
?>
For example:
<?php
$result = interpolate('Hello, #{username}. Welcome to #{site}.', array('username' => 'Hakunin', 'site' => 'php.net'));
?>
28-Apr-2008 12:32
The example presented by bladescope at googlemail dot com has a couple of syntax errors. This works:
<?php
$template = "The {color} {object} is in {location}";
$array = array(
'{object}' => 'Ball',
'{color}' => 'Red',
'{location}' => 'The Playground',
);
foreach ($array as $search => $replace) {
$template = str_replace($search, $replace, $template);
}
print $template;
?>
I did not check it for speed or thoroughly test it, but this function seems to do the same thing more succinctly.
<?php
function template($array, $template) {
return str_replace(
array_keys($array),
array_values($array),
$template
);
}
echo template(
array(
'{color}' => 'red',
'{object}' => 'ball',
'{location}' => 'the playground',
),
'The {color} {object} is in {location}.'
);
?>
09-Aug-2007 09:50
This is the functions I wrote for the problem reported above, str_replace in multi-dimensional arrays. It can work with preg_replace as well.
<?php
function array_replace($SEARCH,$REPLACE,$INPUT) {
if (is_array($INPUT) and count($INPUT)<>count($INPUT,1)):
foreach($INPUT as $FAN):
$OUTPUT[]=array_replace($SEARCH,$REPLACE,$FAN);
endforeach;
else:
$OUTPUT=str_replace($SEARCH,$REPLACE,$INPUT);
endif;
return $OUTPUT;
}
?>
09-Aug-2007 09: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 )
?>
22-Jul-2007 10:28
In order to replace carriage return characters from form inputs, if everything else fails, you can try:
<?php
$new_text = str_replace(chr(13).chr(10), '_', $original_text);
?>
And in order to show the line feeds in a javascript alert, you can do:
<?php
$new_text = str_replace(chr(13).chr(10), '\n', $original_text);
?>
13-Jun-2007 03:47
Here is a version that allows for empty multidimensional arrays:
<?php
function str_replace_array ($search, $replace, $subject) {
if (is_array($subject)) {
foreach ($subject as $id=>$inner_subject) {
$subject[$id]=str_replace_array($search, $replace, $inner_subject);
}
} else {
$subject=str_replace($search, $replace, $subject);
}
return $subject;
}
?>
05-Jun-2007 08: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 02: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 09: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);
&nb