SSISO Community

시소당

str_replace

str_replace
(PHP  3>=  3.0.6,  PHP  4  ,  PHP  5)

str_replace  --    발견한  모든  검색  문자열을  치환  문자열로  교체합니다.  
설명
mixed  str_replace  (  mixed  search,  mixed  replace,  mixed  subject  [,  int  &count])


subject에서  발견한  모든  search를  주어진  replace  값으로  치환한  문자열이나  배열을  반환합니다.  (정규표현식처럼)  복잡한  치환  규칙이  필요하지  않다면,  항상  ereg_replace()나  preg_replace()  대신  이  함수를  사용해야  합니다.  

PHP  4.0.5부터,  str_replace()의  모든  인자를  array로  지정할  수  있습니다.  


주의  
PHP  4.3.3  이전  버전에는  search와  replace  인자에  모두  배열을  사용할  경우,  빈  search  인덱스를  replace  배열의  내부  포인터를  옮기지  않은  채  넘어가는  버그가  존재했습니다.  PHP  4.3.3에서  수정했기에,  이  버그에  관련된  모든  스크립트는  이전의  동작을  하려면  이  함수를  호출  하기  전에  빈  search값을  제거해야  합니다.  
  

subject가  배열이면,  검색  및  치환을  subject의  모든  원소에서  수행하고,  배열을  반환합니다.  

search와  replace가  배열이면,  str_replace()는  각각의  배열에서  가져온  값을  subject의  검색과  치환에  사용합니다.  replace가  search보다  적은  값을  가지면,  나머지  치환값은  빈  문자열을  사용합니다.  search가  배열이고  replace가  문자열이면;  치환  문자열을  모든  search  값에  사용합니다.  

예  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);

//  PHP  5.0.0부터  사용할  수있는  count  인자  사용
$str  =  str_replace("ll",  "",  "good  golly  miss  molly!",  $count);
echo  $count;  //  2
?>    
  


참고:  이  함수는  바이너리  호환(binary-safe)입니다.

참고:  PHP  5.0.0부터  매치하고  치환한  횟수를  참조로  전달하는  count로  반환할  수  있습니다.  PHP  5.0.0  이전에는  이  인자를  사용할  수  없습니다.  

참고:  str_ireplace(),  substr_replace(),  ereg_replace(),  preg_replace(),  strtr().  




  add  a  note  User  Contributed  Notes
str_replace  
spectrereturns  at  creaturestoke  dot  com
23-May-2005  06:53  
This  is  a  little  function  I  wrote  replaces  substrings  in  a  string  with  different  values.  If  there  are  more  instances  of  $search  in  $string  then  there  are  elements  in  $replace,  it  will  start  over.

<?php
    function  replace_different($search,$replace,$string)  {
      $occs  =  substr_count($string,$search);
      $last  =  0;
      $cur  =  0;
      $data  =  '';
      for  ($i=0;$i<$occs;$i++)  {
          $find  =  strpos($string,$search,$last);
          $data  .=  substr($string,$last,$find-$last).$replace[$cur];
          $last  =  $find+strlen($search);
          if  (++$cur  ==  count($replace))  {
              $cur  =  0;
          }
      }
      return  $data.substr($string,$last);
    }
?>

Example:
<?php
$string  =  '`atext`,`btext`';
echo  replace_different('`',array('0~`','1~`'),$string);
?>
Will  return:

0~`atext1~`,0~`btext1~`  
spectrereturns  at  creaturestoke  dot  com
23-May-2005  06:53  
This  is  a  little  function  I  wrote  replaces  substrings  in  a  string  with  different  values.  If  there  are  more  instances  of  $search  in  $string  then  there  are  elements  in  $replace,  it  will  start  over.

<?php
    function  replace_different($search,$replace,$string)  {
      $occs  =  substr_count($string,$search);
      $last  =  0;
      $cur  =  0;
      $data  =  '';
      for  ($i=0;$i<$occs;$i++)  {
          $find  =  strpos($string,$search,$last);
          $data  .=  substr($string,$last,$find-$last).$replace[$cur];
          $last  =  $find+strlen($search);
          if  (++$cur  ==  count($replace))  {
              $cur  =  0;
          }
      }
      return  $data.substr($string,$last);
    }
?>

Example:
<?php
$string  =  '`atext`,`btext`';
echo  replace_different('`',array('0~`','1~`'),$string);
?>
Will  return:

0~`atext1~`,0~`btext1~`  
mdn_abn  at  wp  dot  pl
21-May-2005  07:11  
Little  change  of  code  posted  by  nielsvandenberge  where  is  some  bugs  (text  started  with  [img]name.jpg[/img]  wasn't  showed  and  now  funcions  aren't  recursively  -  now  funcions  run  iteratively)

<?php
function  replaceMessage($message)  {
      $message        =  strip_tags($message,  '<b></b><i></i><u></u><a></a><img>');
    
      $message        =  str_replace  ("\n",  "<BR>",  "$message");
      //  When  you  store  the  $message  in  a  database  you  might  get  errors  cause  of  the  quotes
      $message        =  str_replace("[singleQuote]",  "'",  $message);
      $message        =  str_replace("[doubleQuote]",  "\"",  $message);

      $message        =  str_replace  ("[U]",  "<U>",  "$message");
      $message        =  str_replace  ("[/U]",  "</U>",  "$message");
      $message        =  str_replace  ("[I]",  "<I>",  "$message");
      $message        =  str_replace  ("[/I]",  "</I>",  "$message");
      $message        =  str_replace  ("[B]",  "<B>",  "$message");
      $message        =  str_replace  ("[/B]",  "</B>",  "$message");

      $message        =  replaceUrl($message);
      $message        =  replaceImg($message);
    
      return  $message;
}

function  replaceImg($message)  {
      //  Make  image  from  [img]htp://....  [/img]
      while(strpos($message,  "[img]")!==false){
              $begImg  =  strpos($message,  "[img]");
              $endImg  =  strpos($message,  "[/img]");
              $img  =  substr($message,  $begImg,  $endImg-$begImg+6);
    
              $link                =  substr($img,  5,  $endImg  -  $begImg  -5);
              $htmlImg        =  "<img  src=$link  border='0'>";
          
              $message  =  str_replace($img,  $htmlImg,  $message);
              //  searches  for  other  [img]-nodes
      }
      return  $message;
}

function  replaceUrl($message)  {
      //  Make  link  from  [url]htp://....  [/url]  or  [url=http://....  ]text[/url]
      while(strpos($message,  "[url")!==false){
              $begUrl  =  strpos($message,  "[url");
              $endUrl  =  strpos($message,  "[/url]");
              $url  =  substr($message,  $begUrl,  $endUrl-$begUrl+6);
              $posBracket  =  strpos($url,  "]");
    
              if  ($posBracket  !=  null){
                      if  ($posBracket  ==  4){  
                              //  [url]http://....  [/url]
                              $link                =  substr($url,  5,  $endUrl  -  $begUrl  -5);
                              $htmlUrl        =  "<a  href=$link  target='_blank'>$link</A>";
                      }  else  {                    
                              //  [url=http://....]text[/url]
                              $link                =  substr($url,  5,  $posBracket-5);
                              $text                =  substr($url,  $posBracket+1,  strpos($url,  "[/url]")  -  $posBracket-1);
                              $htmlUrl        =  "<a  href=$link  target='main'>$text</A>";
                      }
              }
                          
              $message  =  str_replace($url,  $htmlUrl,  $message);
              //  searches  for  other  [url]-nodes
      }
      return  $message;
}
?>

Some  other  upgrades  are  possible  :)  
will  at  4lx  dot  net
13-Apr-2005  10:06  
This  function  is  an  example  of  replacing  month  numbers  with  the  actual  textual  value.    

<?php
function  createMonths($month_start,$month_end)  {
      $month  =  array("1",  "2",  "3",  "4",  "5",  "6",
          "7",  "8",  "9",  "10",  "11",  "12");
      $month_replace  =  array("January","February","March","April","May","June",
      "July","August","September","October","November",  "December");
      $x_end  =  $month_end  +  1;  
      //  Add  one  to  the  value  of  the  end  month
      for  ($x  =  $month_start;  $x  <  $x_end;  $x++)  {
              $new_months  .=  $x.",";  
              //  Count  from  the  begin  month  to  the  end  month
              }
              $new_months  =  substr($new_months,0,-1);  
              //  Cut  the  last  comma  off  the  end  month
              $newmonth  =  explode(",",  $new_months);  
              //  Place  each  int  month  into  an  array
              $newsmonth  =  str_replace($month,$month_replace,$newmonth);  
              //  Replace  the  int  month  with  a  textual  string
              var_dump  ($newsmonth);  
              //  Dump  the  data
      }
createMonths(1,3);
/*  Will  print  array(3)  
{  [0]=>  string(7)  "January"  [1]=>  string(8)  "February"  [2]=>  string(5)  "March"  }  */
?>  
james  dot  robert  dot  lee  at  gmail  dot  com
13-Apr-2005  05:01  
"Note:    As  of  PHP  5.0.0  the  number  of  matched  and  replaced  needles  (search)  will  be  returned  in  count  which  is  passed  by  reference.  Prior  to  PHP  5.0.0  this  parameter  is  not  available."

In  version  4.3.10  and  I  assume  others  before  5.0.0,  str_replace  returns  null  if  you  pass  it  a  $count.

<?php
$count  =  0;
$str  =  "This  is  a  string";
$str  =  str_replace("a",  "a  null",  $str,  $count);

if  (is_null($str))  {    //  TRUE  before  php  5.0.0
      echo  "NULL";
}
?>

Fortunately,  this  does  produce  a  warning:  "Wrong  parameter  count  for  str_replace()"  
a_baboshin  at  mail  dot  ru
04-Apr-2005  11:00  
I  wrote  2  function's  file_replace()  and  dir_replace()  with  str_replace()  signature

      function  file_replace  ($search,  $replace,  $filename)  {
              if  (file_exists($filename))  {
                      $cnt  =  file_get_contents($filename);
                      if  (strstr($cnt,  $search))  {
                              $cnt  =  str_replace($search,  $replace,  $cnt);
                              return  file_put_contents($filename,  $cnt);
                      }
                      return  true;
              }
              return  false;
      }
      
      function  dir_replace  ($search,  $replace,  $dirname,  $recursive  =  true)  {
              $dir  =  opendir($dirname);
              while  ($file  =  readdir($dir))  {
                      if  ($file  !=  '.'  &&  $file  !=  '..')  {
                              if  (is_dir($dirname.'/'.$file))  {
                                      if  ($recursive)  {
                                              dir_replace($search,  $replace,  $dirname.'/'.$file);
                                      }
                              }  else  {
                                      file_replace($search,  $replace,  $dirname.'/'.$file);
                              }
                      }
              }
      }

usage  ('search',  'replace',  '/usr/home/root');  
joaquin  at  metaltoad  dot  com
25-Mar-2005  09:04  
This  is  an  another  accent  remover  which  converts  foreign  characters  to  their  English  equivilent.  It  converts  any    character's  to  their  HTML  value  and  then  uses  preg_replace  to  find  the  desired  value.    The  function  is  based  on  a  earlier  entry:  replace_accents.

function  remove_accents(  $string  )
{
      $string  =  htmlentities($string);
      return  preg_replace("/&([a-z])[a-z]+;/i","$1",$string);
}

example:

$string  =  "&#43623;?;
echo  remove_accents(  $string  );

//  will  output:  eecyCECA  
Gabriel  W&#19629;by
16-Mar-2005  10:36  
Note  that  when  using  the  str_replace  function  it  will  always  replace  the  already  replaced  parts  in  a  String  even  if  you  just  allow  replacement  of  one  character  at  a  time.
[php]
$thecode  =  '453461';
for  ($t=0;  $t<=5;  $t++){
$index  =  substr($thecode,$t,1);
$digits  =  array(1,  2,  3,  4,  5,  6);
$newdigits    =  array(4,  5,  2,  7,  8,  0);
$realcode.=  str_replace($digits,  $newdigits,  $index);
}
/*Would  print  out  '782707'  instead  of  '7827704'  as  it  should  with  this  construction.*/
echo  $realcode;
[/php]  
nielsvandenberge  at  hotmail  dot  com
14-Mar-2005  07:12  
I  got  a  few  things  to  add  on  the  subject  Jesse  posted  about  the  smiley  replacement.  

Bad  HTML  code  can  be  removed  with  the  php  function  strip_tags().

Further  I  would  like  to  add  my  URL-  and  IMG-replace  function.  The  problem  was  that  it  would  only  replace  one  IMG  or  URL  node,  but  since  the  functions  calls  itself  until  there  aren't  IMG  or  URL-nodes  anymore  they  will  all  be  replaced.

Note  that  the  replace  function  is  case  sensitive,  so  for  example  [b]  won't  be  replaced.

Regards,

Here's  the  code:
<?php
function  replaceMessage($message)  {
      $message        =  strip_tags($message,  '<b></b><i></i><u></u><a></a><img>');
      
      $message        =  str_replace  ("\n",  "<BR>",  "$message");
      //  When  you  store  the  $message  in  a  database  you  might  get  errors  cause  of  the  quotes
      $message        =  str_replace("[singleQuote]",  "'",  $message);
      $message        =  str_replace("[doubleQuote]",  "\"",  $message);

      $message        =  str_replace  ("[U]",  "<U>",  "$message");
      $message        =  str_replace  ("[/U]",  "</U>",  "$message");
      $message        =  str_replace  ("[I]",  "<I>",  "$message");
      $message        =  str_replace  ("[/I]",  "</I>",  "$message");
      $message        =  str_replace  ("[B]",  "<B>",  "$message");
      $message        =  str_replace  ("[/B]",  "</B>",  "$message");

      $message        =  replaceUrl($message);
      $message        =  replaceImg($message);
      
      return  $message;
}

function  replaceImg($message)  {
      //  Make  image  from  [img]htp://....  [/img]  
      if  (strpos($message,  "[img]")){
              $begImg  =  strpos($message,  "[img]");
              $endImg  =  strpos($message,  "[/img]");
              $img  =  substr($message,  $begImg,  $endImg-$begImg+6);
      
              $link                =  substr($img,  5,  $endImg  -  $begImg  -5);
              $htmlImg        =  "<img  src=$link  border='0'>";
              
              $message  =  str_replace($img,  $htmlImg,  $message);
              //  searches  for  other  [img]-nodes
              $message  =  replaceImg($message);
      }
      return  $message;
}

function  replaceUrl($message)  {
      //  Make  link  from  [url]htp://....  [/url]  or  [url=http://....  ]text[/url]
      if  (strpos($message,  "[url")){
              $begUrl  =  strpos($message,  "[url");
              $endUrl  =  strpos($message,  "[/url]");
              $url  =  substr($message,  $begUrl,  $endUrl-$begUrl+6);
              $posBracket  =  strpos($url,  "]");
      
              if  ($posBracket  !=  null){
                      if  ($posBracket  ==  4){    
                              //  [url]http://....  [/url]
                              $link                =  substr($url,  5,  $endUrl  -  $begUrl  -5);
                              $htmlUrl        =  "<a  href=$link  target='_blank'>$link</A>";
                      }  else  {                        
                              //  [url=http://....]text[/url]
                              $link                =  substr($url,  5,  $posBracket-5);
                              $text                =  substr($url,  $posBracket+1,  strpos($url,  "[/url]")  -  $posBracket-1);
                              $htmlUrl        =  "<a  href=$link  target='main'>$text</A>";
                      }
              }
                              
              $message  =  str_replace($url,  $htmlUrl,  $message);
              //  searches  for  other  [url]-nodes
              $message  =  replaceUrl($message);
      }
      return  $message;
}
?>  
Jesse
08-Mar-2005  02:41  
str_replace  can  do  many  things,  including  smileys,  bad  word  replacement,  and  even  manually  taking  out  bad  HTML  code.  doing  smileys  is  easy,  first,  create  a  jpg  called  smiley  and  add  the  following  code  to  your  form  handling  script:
$posting  =  str_replace(":)",  "<img  src=smiley.jpg  width=50  height=50>",  $posting);
also,  taking  out  bad  words  is  easy,  too:
$posting  =  str_replace("badword",  "*******",  $posting);
then,  lets  say  you  want  a  form  handler  that  keeps  some  HTML  code  to  let  people  do  things  like  post  images,  but  not  let  them  change  the  page's  formatting.  use  str_replace!
$posting  =  str_replace("BADHTMLCODE",  "",  $posting);
finally,  you  can  even  make  a  scripting  language  like  vBcode,  like  this:
$posting  =  str_replace("[IMG]",  "<img  src>",  $posting);
$posting  =  str_replace("[URL]",  "<a  href>",  $posting);
$posting  =  str_replace("[/URL]",  "</a>",  $posting);
$posting  =  str_replace("[CODE]",  "<pre><p>code:</p>",  $posting);
$posting  =  str_replace("[/CODE]",  "</pre>",  $posting);
The  list  of  things  you  can  do  goes  on  and  on!  
somewhereinspace  at  deepspace  dot  com
07-Mar-2005  10:33  
This  is  an  reply  to  Adam  F-K's  alphanumeric  check:
I  guess  my  function  does  the  same,  but  a  bit  quicker

<?php
      //  Checks,  if  the  String  contains  only  allowed  Chars
      //  edit  the  RegEx  if  you  need  other  chars  as  well
      //  for  example:  [^A-Za-z&#994740;?誡&#2338;&#1234;&#1428;&#1818;&#1627;?&#132;  .-]
      //  return  true  or  false
      function  isAlphaNumeric(  $str  )
      {
              $len_org  =  strlen(  $str  );
              $len_chk  =  strlen(  ereg_replace(  "[^A-Za-z0-9]",  "",  $str  )  );
              return  $len_org  ==  $len_chk;
      }
?>

Ronald  L.  
Anca  Zaharia(anca  dot  zaharia  at  grapefruit  dot  ro)
04-Mar-2005  07:33  
Simple  function  to  strip  multiple  white  spaces  in  a  string:

$sample  =  preg_replace('/\s\s+/',  '  ',  $sample);  
dambkruck  AT  hotmail  dot  com
24-Feb-2005  12:37  
I'm  not  sure  that  this  is  the  right  place,  but  I  believe  that  it  is  useful  for  the  accents  problem.    I  just  wrote  and  tested  this  script  because  I'm  using  a  variable  from  $_GET  to  open  a  text  file  and  I  do  not  want  to  allow  anyone  to  go  searching  thru  my  folders  by  entering  ../  (or  other  malicious  stuff  that  I  don't  know  about).    Anyway,  this  function  returns  true  if  the  string  passed  to  it  is  only  made  up  of  letters  (upper/lower  case)  or  numbers.

<?PHP
//-------------------------------------------------------------------
//allowed  chars  from  48-57,65-90,97-122  AKA  0-9,  A-Z,  a-z
//-------------------------------------------------------------------
function  isAlphaNumeric($checkThisString){
      $result  =  true;
      $i=0;
      while($i<strlen($checkThisString)  &&  $result){
              $char  =  substr($checkThisString,$i,1);
              $charNum  =  ord($char);
              if(  !(($charNum>47  &&  $charNum  <  58)  ||  ($charNum>64  &&  $charNum  <  91)  ||  ($charNum>96  &&  $charNum  <  123))  )
                      $result  =  false;                
              $i++;
      }
      return  $result;
}
?>

cheers,

Adam  F-K  
cjo  at  ciqua  dot  org
17-Feb-2005  09:29  
In  order  to  get  rid  of  accents,  we  don't  need  to  reach  as  far  out  as  the  ascii  tables.  HTML  has  the  lovely  property  that  accents  are  added  to  the  character  X  in  the  form  &Xmodif;  where  modif  stands  for  the  modification  of  the  original  character:  acute,  grave,  uml,  etc.
There  are  far  fewer  accents  than  accented  letters  so  this  should  do  the  trick  whether  or  not  it  is  intended  for  HTML  or  not:

function  replace_accents($in_string)
{
      $out_string  =  htmlentities($in_string);

      $out_string  =  str_replace("uml;",  "",  $out_string);
      $out_string  =  str_replace("acute;",  "",  $out_string);
      $out_string  =  str_replace("grave;",  "",  $out_string);
      $out_string  =  str_replace("cedil;",  "",  $out_string);
      $out_string  =  str_replace("ring;",  "",  $out_string);
      $out_string  =  str_replace("circ;",  "",  $out_string);
      $out_string  =  str_replace("tilde;",  "",  $out_string);
      $out_string  =  str_replace("lig;",  "",  $out_string);
      $out_string  =  str_replace("slash;",  "",  $out_string);

      $out_string  =  str_replace("&",  "",  $out_string);
      return  $out_string;
}

The  function  above  assumes  there  are  only  letter  in  the  input  (no  ampersand,  <  and  >,  quotes,  etc).  I  hope  this  helps!  
hermes  at  andycostell  dot  com
12-Dec-2004  04:57  
A  simple  function  to  take  out  the  double  line  breaks  "%0D%0A"  from  a  string  made  from  text  being  wrapped  in  a  textarea  and  turn  them  into  single  line  breaks.  

<?php
function  remove_extra_linebreaks($string)  {
          $new_string=urlencode  ($string);
      $new_string=ereg_replace("%0D",  "  ",  $new_string);
      $new_string=urldecode    ($new_string);
    return  $new_string;
}
?>

I  use  it  when  taking  text  from  a  textarea  with  wrap="hard"  that  I'm  emailing  out  on  the  next  page,  for  instance.  Otherwise  there's  an  extra  empty  line  between  each  line  in  the  emailed  text,  which  looks  nasty!  
21-Nov-2004  04:08  
---[  Editor's  Note  ]---  
This  way  works,  but  it's  easier  to  just  use  nl2br()  instead,  which  supports  both  \n  and  \r,  whereas  this  function  does  not  support  both.  
---[  End  Note  ]---  

This  is  an  easy  way  to  replace  the  breaks  and  paragrafs  submitted  via  a  Textarea  to  <br>s  in  the  output.  

<?Php  
$test="Teststring  
test  test  
test  test  test  test";  

echo  str_replace(Chr(13),  "<br>",  $test);  
?>  
Jennings  at  trad  dot  uji  dot  es
10-Nov-2004  10:09  
Removing  accents.
It  is  a  pain  to  list  all  the  accented  characters  you  think  you  will  come  across  -  and  you  never  know  when  someone  is  going  to  use  an  unexpected  '?r  other  such  obscure  character.
In  the  HTML  Entities  table  the  accented  characters  are  described  in  such  a  way  that  the  second  character  (ie  the  one  after  after  the  ampersand)  is  always  the  same  as  the  unaccented  form  of  the  accented  letter  (and  in  the  same  case).  '&#551;,  for  example,  is  '&Eaccute;'.  
This  function  takes  advantage  of  that  fact  and  removes  all  accents.

<?php
function  unaccent($text){
$trans  =  get_html_translation_table(HTML_ENTITIES);  //Get  the  entities  table  into  an  array
foreach  ($trans  as  $literal  =>$entity){  //Create  two  arrays,  for  accented  and  unaccented  forms
      if  (ord($literal)>=192){  //Don't  contemplate  other  characters  such  as  fractions,  quotes  etc
          $replace[]=substr($entity,1,1);  //Get  'E'  from  string  '&Eaccute'  etc.
          $search[]=$literal;}}  //Get  accented  form  of  the  letter
return  str_replace($search,  $replace,  $text);}

echo  unaccent("H&#43820;&#655926;&#40127;?");

?>  
jschultz  at  youritdepot  dot  com
20-Aug-2004  06:40  
Instead  of  using  function  str_replace_clean()  posted  by  Jeroen  use  strtr().

Here  is  the  problem  str_replace_clean()  fixes:
$search  =  array("one",  "two",  "three");
$replace  =  array("two",  "three",  "one");
$subject  =  "one  two  three";
str_replace($search,  $replace,  $subject);  
Output:  "one  one  one".
str_replace_clean($search,  $replace,  $subject);  
Output:  "three  two  one".

Instead  use  strtr()  as  so:
$trans  =  array(
"one"  =>  "two",
"two"  =>  "three",
"three"  =>  "one",
);
strtr($subject,  $trans);
Output:  "three  two  one".

Hope  this  helps  someone.
I  used  it  to  replace  emoticon  codes  :)  with  image  tags,  and  it  works  great  
Jeroen  -  http://jeroen.all-stars.nl
28-Jun-2004  08:15  
For  a  comparison  of  function  str_replace_clean()  with  standard  function  str_replace(),  I've  put  two  testprograms  at  my  website:  see  http://jeroen.all-stars.nl/php.php  and  click  link  'Function  str_replace_clean()'.
You  can  also  download  the  code  there.  
aidan  at  php  dot  net
27-Jun-2004  02:53  
Here  is  a  simple  function  for  highlighting  a  needle  in  text.  It  is  careful  to  not  replace  text  in  HTML  tags  (unless  specified).  

http://aidan.dotgeek.org/lib/?file=function.str_highlight.php  


Example:  The  google  method  of  highlighting  

<?php  
$text  =  "Here  is  some  text  with  a  search  term";  
$needle  =  "search  term";  
echo  str_highlight($text,  $needle);  
?>  

Output:  
Here  is  some  text  with  a  <strong>search  term</strong>  
aidan  at  php  dot  net
27-Jun-2004  02:07  
If  you  would  like  to  convert  tabs  to  spaces,  you  could  use  the  code:  

<?php  
str_replace("\t",  "        ",  $text);  
?>  

However,  sometimes  this  is  not  good  enough.  To  be  technically  correct,  a  tab  is  not  4  spaces,  a  tab  shifts  the  text  to  the  next  predefined  column.  Usually  these  predefined  columns  occur  every  4  spaces  from  the  start  of  the  line.  

If  you  want  to  convert  tabs  to  spaces  while  ensuring  consistant  formatting,  try  this  function...  

http://aidan.dotgeek.org/lib/?file=function.tab2space.php  
rylas  at  mudmirror  dot  com
04-Jun-2004  07:48  
An  easy  way  to  convert  email  addresses  to  the  PHP.net  comment-style  email  addresses:  

<?  
$email  =  "john@doe.org";  
$search  =  array('@',  '.');  
$replace  =  array("  at  ",  "  dot  ");  
$result  =  str_replace($search,  $replace,  $email);  
?>  

Outputs:  
john  at  doe  dot  org  
jr  at  adslate  dot  com
03-Jun-2004  09:52  
When  the  first  argument  to  str_replace()  is  an  array,  the  elements  are  checked  in  increasing  order  of  array  index,  as  one  would  expect.  

For  example,  

str_replace  (array  ('ABC',  'BC'),  array  ('E',  'F'),  'ABC')  
returns  'E';  

str_replace  (array  ('BC',  'ABC'),  array  ('E',  'F'),  'ABC')  
returns  'AE'.  
aeron  at  aeronius  dot  org
23-May-2004  07:05  
Here's  something  I  used  to  utilize  str_replace  in  a  script,  by  using  it  to  replace  text  with  graphic  images..  say,  if  you  had  a  counter  or  whatnot,  and  wanted  a  way  to  make  the  counter's  results  graphical:  

<?  
//  For  here,  we're  going  to  create  a  $  number  ..  
$num  =  56;  

//  now,  for  the  str_replace  arrays.    We'll  need  these  to  make  the  replacements.  
    
//  digits  to  search  for  
$nums  =  array  (  "1",  "2",  "3",  "4",  "5",  "6",  "7",  "8",  "9",  "0"  );  
    
//  images  array  to  replace  them  with.  
$images  =  array  (  "<img  src=1.gif>",  "<img  src=2.gif>"  ,  "<img  src=3.gif>"  );  
//  continue  with  the  <img  src>'s  with  the  number  pattern  above.  
    
//  Now,  for  the  function  to  do  all  the  replacing.  
$final  =  str_replace  ($nums,  $images,  $num);  
    
echo  $final;  
?>  

Quite  simple,  really.  
bookvii  at  hotmail  dot  com
18-May-2004  03:07  
this  is  a  rather  long  and  obvious  solution  to  converting  non-english  chars  where  str_replace  fails.  

<?php  
function  euro_chars($str)  
{  
              $tmp  =  "";  
              for($i  =  0;  $i  <  strlen($str);  $i++)  {  
                              switch(ord($str[$i]))  {  
                                              case  192:  case  193:  //??
                                                              $tmp  .=  "A";  
                                                              break;  
                                              case  200:  case  201:  //&#544;&#589;
                                                              $tmp  .=  "E";  
                                                              break;  
                                              case  204:  case  205:  //&#800;&#845;
                                                              $tmp  .=  "I";  
                                                              break;  
                                              case  210:  case  211:  //&#1184;&#1229;
                                                              $tmp  .=  "O";  
                                                              break;  
                                              case  217:  case  218:  //&#1632;&#1677;
                                                              $tmp  .=  "U";  
                                                              break;  
                                              case  224:  case  225:  //&#2081;  
                                                              $tmp  .=  "a";  
                                                              break;  
                                              case  232:  case  233:  //&#34857;  
                                                              $tmp  .=  "e";  
                                                              break;  
                                              case  236:  case  237:  //젭  
                                                              $tmp  .=  "i";  
                                                              break;  
                                              case  242:  case  243:  //&#658637;
                                                              $tmp  .=  "o";  
                                                              break;  
                                              case  249:  case  250:  //?br  />                                                                $tmp  .=  "u";  
                                                              break;  
                                              case  241:  //&#319266;r  />                                                                $tmp  .=  "n";  
                                                              break;  
                                              case  209:  //э
                                                              $tmp  .=  "N";  
                                                              break;  
                                              case  231:  //&#29564;br  />                                                                $tmp  .=  "c";  
                              break;  
                                              case  199:  //&#461;
                                                              $tmp  .=  "C";  
                                                              break;  
                                              case  128:  //?  
                                                              $tmp  .=  "EU";  
                                                              break;  
                                              default:  
                                                              $tmp  .=  (string)$str[$i];  
                                                              break;  
                              }  
              }  
              return($tmp);  
}  
?>  
sonicavanger  at  copyleft  dot  com
02-Apr-2004  09:35  
This  function  was  originally  written  to  produce  UNIX  and  Windows  conform  Filenames  from  DB  ::  Firstname,  Lastname.  

<?php  
//  ---------------------------------------------------------  
//  function  forceFilename($str,  $spaceChar)  
//  
//  convert  $str  to  a  UNIX/Windows-conform  filename  
//  a  char  for  $spaceChar  will  replace  the  default  whitespace  '_'  
//  note  when  using  '.'  internet  exploer  adds  automatically  "[1]"  
//  for  e.g.  "This[1].is.a.filename.ext"  in  the  save  as  dialog.  
//  ---------------------------------------------------------  

function  forceFilename($str,  $spaceChar  =  '_')  
{  
    
    $str=trim($str);  
    
    $_str  =  '';  
    $i_max  =  strlen($str);  
    for  ($i=0;  $i<strlen($str);  $i++)  
    {  
      $ch  =  $str[$i];  
      switch  ($ch)  
      {  
          case  'ħ:  case  '&#423;:  
          $_str  .=  'AE';  break;        
          
          case  '&#18940;/span>:  case  '&#27132;/span>:  
          $_str  .=  'ae';  break;  
          
          case  '&#2556;/span>:  case  '&#6652;/span>:    case  '&#10748;/span>:  case  '&#14844;/span>:    case  '&#23036;/span>:  
          $_str  .=  'a';  break;        
          case  '?:  case  '?:    case  '§:  case  '&ccedil;:    case  'ŧ:  
          $_str  .=  'a';  break;        
          
          case  '&#487;:  case  '&#31228;/span>:  
          $_str  .=  'c';  break;  
    
          case  '&#35324;/span>:  case  '&#39420;/span>:    case  '&#43516;/span>:  case  '&#47612;/span>:  
          $_str  .=  'e';  break;        
          
          case  '&#551;:  case  '&#615;:    case  '&#679;:  case  '&#743;:  
          $_str  .=  'E';  break;        
          
          case  '&#807;:  case  '&#871;:    case  'Χ:  case  '&#999;:  
          $_str  .=  'I';  break;        
          case  '짼/span>:  case  '&#55804;/span>:    case  '&#59900;/span>:  case  '識/span>:  
          $_str  .=  'i';  break;        
          
          case  '&#1127;:  case  '&#425775;span>:  
          $_str  .=  'n';  break;  
          
          case  '&#1447;:    
          $_str  .=  'OE';  break;  
          
          case  '?span>:  
          $_str  .=  'oe';  break;  
          
          case  '&#1191;:  case  '&#1255;:    case  '&#1319;:  case  '&#1383;:  
          $_str  .=  'O';  break;        
          case  '&#687919;span>:  case  '&#950063;span>:    case  '?span>:  case  '?span>:  
          $_str  .=  'i';  break;        
          
          case  '&#2023;:  
          $_str  .=  'ss';  break;  
          
          case  '&#1639;:  case  '&#1703;:    case  '&#1767;:  
          $_str  .=  'U';  break;        
          case  '?pan>:  case  '?pan>:    case  '?pan>:  
          $_str  .=  'u';  break;        
          
          case  '&#1831;:  
              $_str  .=  'UE';  break;  
              
          case  '?an>:  
          $_str  .=  'ue';  break;  
          
          case  '&#1895;:  
              $_str  .=  'Y';  break;  
              
          case  '?an>:  case  '?span>:  
          $_str  .=  'y';  break;  
          
          case  'Ч:  
          $_str  .=  'D';  break;  
          
          case  '  ':  $_str  .=  $spaceChar;  break;  

          case  '/':  case  '\'':  case  '-':  case  ':':  
          $_str  .=  '-';  break;  
          
          default  :  if  (ereg('[A-Za-z0-9\(\)]',  $ch))  {  $_str  .=  $ch;    }  break;  
      }  
    }        
      
    $_str  =  str_replace("{$spaceChar}{$spaceChar}",  "{$spaceChar}",  $_str);  
    $_str  =  str_replace("{$spaceChar}-",  '-',  $_str);  
    $_str  =  str_replace("-{$spaceChar}",  '-',  $_str);  
    
    return  $_str;  
}  
?>  
calin  at  php9  dot  com
19-Mar-2004  03:52  
As  the  manual  clearly  states,  it  is  only  after  PHP  4.0.5  that  every  parameter  in  str_replace()  can  be  an  array.  

However  you  can  use  this  function  with  arrays:  

<?php  
str_replace($array1,$array2,$dest)  
?>  

Before  4.0.5  and  str_replace  will  silently  do  nothing.  
Darren  Gates  -  http://www.tufat.com
15-Mar-2004  06:22  
Here's  a  version  of  str_replace  which  ignores  differences  in  spacing  (like  tab,  carriage  return,  line  feed,  etc.)  in  the  two  input  strings.  

Courtesy  of  http://www.tufat.com  (Darren's  Script  Archive).  

<?php  
function  str_rep($srcfor,$chwith,$mystr)  
{  
      if(strlen($mystr)  ==  0)  
              return  "";  

      $tok    =  strtok($srcfor,"  \n\t\r");  
      $strsrc  =  array();  
      $idxsrc  =  array();  
      $i  =  0;  
      while($tok)  
      {  
              $strsrc[$i]  =  $tok;  
              $pos  =  strpos($srcfor,$tok);  
              $idxsrc[$i]=$pos;  
              $tok  =  strtok("  \n\r\t");  
              $i++;  
      }  

      $tok2    =  strtok($mystr,"  \n\t\r");  
      $str  =  array();  
      $idx  =  array();  
      $j  =  0;  

      while($tok2)  
      {  
              $str[$j]  =  $tok2;  
              $pos  =  strpos($mystr,$tok2);  
              $idx[$j]=$pos;  
              $tok2  =  strtok("  \n\r\t");  
              $j++;  
      }  

      for($m=0;$m<$j;$m++)  
      {  
              if(strcasecmp($strsrc[0]  ,  $str[$m])  ==  0)  
              {  
                      for($l=1;$l<$i;$l++)  
                      {  
                              if(strcasecmp($strsrc[$l],$str[$m+$l])  !=  0)  
                                      break;  
                      }  
                      $l--;  
                      if(($l+1)  ==  $i)  
                      {  

                              $new_str=substr($mystr,0,$idx[$m]);  
                              $new_str  .=  $chwith;  

                              $index  =  $idx[$m+$l]+strlen($str[$l+$m]);  
                              $len  =  strlen($mystr)-$index;  

                              if($len  >  0)  
                                      $new_str  .=  str_rep($srcfor,$chwith,substr($mystr,$index,$len));  

                              return  $new_str;  
                              break;  
                      }  

              }  
      }  

      return  $mystr;  
}  
?>  
unusedacct  at  no$p  at  m  dot  comcast  dot  net
20-Feb-2004  02:45  
For  those  who  haven't  yet  updated  to  PHP  5  yet,  here  is  a  quick  function  to  do  regular  str_replace  on  a  string  [not  arrays]  only  a  certain  number  of  times:

<?php

function  str_replace_count($find,$replace,$subject,$count)
{
      $subjectnew  =  $subject;
      $pos  =  strpos($subject,$find);
      if  ($pos  !==  FALSE)
      {
          while  ($pos  !==  FALSE)
          {
                  $nC  =  $nC  +  1;
                  $temp  =  substr($subjectnew,$pos+strlen($find));
                  $subjectnew  =  substr($subjectnew,0,$pos)  .  $replace  .  $temp;
                  if  ($nC  >=  $count)
                  {
                      break;
                  }
                  $pos  =  strpos($subjectnew,$find);
          }  //  closes  the  while  loop
      }  //  closes  the  if
      return  $subjectnew;
}

$stuff  =  "a  b  a  b  a  b  a  b  a";

print  $stuff  .  "  --  the  old  string<br>\n";

print  str_replace_count("a  ","c  ",$stuff,4)  .  "  --  the  new  string<br>\n";
//  will  output  c  b  c  b  c  b  c  b  a  --  the  new  string

?>

Hope  this  helps.  
xavier  paz  (xpaz  at  matadracs  dot  com)
31-Dec-2003  03:39  
If  both  the  search  and  replace  params  are  arrays,  str_replace()  will  apply  the  substitutions  incrementally,  it  is,  it  will  try  the  first  substitution,  then  the  second  using  the  result  from  the  first  one,  and  so  on.  It  may  be  OK,  or  it  may  be  a  problem  if  you  only  want  to  change  the  original  text.  

For  example,  consider  this  code:  
<?php  
$search  =  array("one",  "two",  "three");  
$replace  =  array("two",  "three",  "one");  
$subject  =  "one  two  three";  
echo  str_replace($search,  $replace,  $subject).  "<br>";  
//  echoes  "one  one  one"  
?>  

This  function  makes  the  substitutions  only  to  the  original  text.  

<?php  
/**  
  *  same  as  str_replace  (array,  array,  string),  but  changing  only  the  text  in  the  
  *  original  string  
  *  $search  and  $replace  are  arrays  of  strings,  $subject  is  a  string  
  */  
function  str_replace_clean($search,  $replace,  $subject)  {  
      if  (!is_array($search)  or  !is_array($replace)  or  !is_string($subject))  return  $subject;  
      while  (count($search))  {  
              //  get  current  terms,  reduce  the  arrays  for  the  next  iteration  
              $search_text  =  array_shift($search);  
              $replace_text  =  array_shift($replace);  
              //  check  if  the  substring  is  present  
              $pos  =  strpos($subject,  $search_text);  
              if  (is_int($pos))  {  
                      //  match  found  -  break  in  pieces  
                      $pieces  =  explode($search_text,  $subject);  
                      if  (count($search))  {  //  only  if  there  are  more  substitutions  to  do  
                              //  make  next  substitutions  in  every  piece  of  text  between  matches  
                              foreach  ($pieces  as  $k  =>  $v)  {  
                                      if  (strlen($v))  $pieces[$k]  =  str_replace_clean($search,  $replace,  $v);  
                              }  
                      }  
                      $subject  =  join($replace_text,  $pieces);  
                      break;  
              }  
      }  
      return  $subject;  
}  
?>  

To  test:  
<?php  
echo  str_replace_clean($search,  $replace,  $subject);  
//  echoes  "two  three  one"  
?>  

--  Xavier  
thewolf  at  pixelcarnage  dot  com
23-Oct-2003  11:45  
I  also  wanted  to  replace  rude  words  in  a  pice  of  text,  I  had    str_replace  replacing  the  word  with  ***  but  then  I  had  a  thought,  what  if  I  could  replace  these  bad  words  and  words  also  very  similar?  In  the  end  I  wrote  this  code,  it  uses  two  functions,  one  to  check  if  the  similarity  between  two  words  is  high  enough  to  qualify  for  filtering  out  and  one  to  do  the  actual  replacing  (modified  from  my  word_replace  function):  

<?php  
$text  =  'This  is  some  text  with  a  baword  in  it.';  
echo  similar_str_replace('badword',  '*******',  $text,  80);  
      
function  is_similar($one,  $two,  $similarity)  {  
      similar_text($one,  $two,  $percent);  
      return  $percent  >=  $similarity  ?  true  :  false;  
}  

/**  
  *  Written  by  Rowan  Lewis  of  PixelCarnage.com  
  *  $search(string),  the  string  to  be  searched  for  
  *  $replace(string),  the  string  to  replace  $search  
  *  $subject(string),  the  string  to  be  searched  in  
  *  $similarity(int),  how  similar  the  two  words  must  be  
  */  
function  similar_str_replace($search,  $replace,  $subject,  $similarity  =  85)  {  
      return  preg_replace('/[a-zA-Z]+/e',  'is_similar(\'\0\',  \''  .  $search  .  '\',  \''  .  $similarity  .  '\')  ?  \''  .  $replace  .  '\':  \'\0\';',  $subject);  
}  
?>  

Just  wack  that  into  a  php  file,  its  ready  for  testing!  

Hope  someone  uses  it,  and  perhaps  improves  it  somehow.  
thewolf  at  pixelcarnage  dot  com
23-Oct-2003  11:38  
I  got  sick  of  trying  to  replace  just  a  word,  so  I  decided  I  would  write  my  own  string  replacement  code.  When  that  code  because  far  to  big  and  a  little  faulty  I  decided  to  use  a  simple  preg_replace:  

<?php  
/**  
  *  Written  by  Rowan  Lewis  of  PixelCarnage.com  
  *  $search(string),  the  string  to  be  searched  for  
  *  $replace(string),  the  string  to  replace  $search  
  *  $subject(string),  the  string  to  be  searched  in  
  */  
function  word_replace($search,  $replace,  $subject)  {  
      return  preg_replace('/[a-zA-Z]+/e',  '\'\0\'  ==  \''  .  $search  .  '\'  ?  \''  .  $replace  .  '\':  \'\0\';',  $subject);  
}  
?>  

I  hope  that  this  code  helpes  someone!  
t  at  seebach  dot  dk
16-Oct-2003  09:58  
A  simple  way  of  making  a  case  insensitive,  multiple  words  (array)  highligt  of  a  string:  

<?php  
$needle  =  array("foo","bar","boo");  

//  use  the  |  to  make  preg_replace  to  use  multiple  values  
$needle  =  join('|',$needle);  

//  use  the  /i  to  make  case  insensitive  and  \\0  not  replace  th  word  but  simply  to  wrap  the  word.  

$text  =  preg_replace("/($needle)/i","<b>\\0</b>",$haystack);  
?>        

Hope  you  can  use  it,  enjoy  Torben  
David  Gimeno  i  Ayuso  (info  at  sima-pc  dot  com)
25-Aug-2003  10: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".  
imho  at  auspantheon  dot  com
27-Jun-2003  08:08  
An  excellent  way  of  making  sure  your  pages  don't  contain  "invalid  entities",  IE.  Valid  HTML  is  using  the  following  function.  

Most  forum  packages  /  extensions  provide  output  containing  the  symbol  &,  we  don't  want  this!  

<?php  
function  include_safe  ($file)  
{  
      $array  =  file($file);  

      foreach  ($array  as  $line)  {  
      print  str_replace('&',  '&amp;',  $line);  
      }  
}  
?>  

The  same  technique  could  also  be  used  in  conjuntion  with  htmlmspecialchars  or  htmlentities.  
dbergeron  [at]  clincab  [dot]  com
26-Jun-2003  03:08  
here  is  a  function  to  highlight  a  part  of  a  string.  Unlike  str_replace,  it  is  both  case  insensitive,  and  maintains  the  case  of  the  highlighted  text.  

<?php  
function  highlight($x,$var)  {//$x  is  the  string,  $var  is  the  text  to  be  highlighted  
      if  ($var  !=  "")  {  
              $xtemp  =  "";  
              $i=0;  
              while($i<strlen($x)){  
                      if((($i  +  strlen($var))  <=  strlen($x))  &&  (strcasecmp($var,  substr($x,  $i,  strlen($var)))  ==  0))  {  
//this  version  bolds  the  text.  you  can  replace  the  html  tags  with  whatever  you  like.  
                                      $xtemp  .=  "<b>"  .  substr($x,  $i  ,  strlen($var))  .  "</b>";  
                                      $i  +=  strlen($var);  
                      }  
                      else  {  
                              $xtemp  .=  $x{$i};  
                              $i++;  
                      }  
              }  
              $x  =  $xtemp;  
      }  
      return  $x;  
}  
?>  

Example:  
<?php  
$string  =  "AaBbCcDd";  
$string  =  highlight($string,  "bc");  
echo  $string;  //AaB<b>bC</b>cDd  
?>  
13-Jun-2003  07:59  
Having  a  string  for  $search  and  an  array  for  $replace  won't  work.  This  is  mentioned  on  the  preg_replace()  page  where  it's  described  as  not  making  sense,  but  not  here.  

But  one  could  interpret  such  a  situation  and  hence  implement  str_replace  so  that  a  signature  of  (string,  array,  string)  or  even  (string,  array,  array)  would  "work".  The  result  of  

<?php  
$search  =  '*';  
$replace  =  range(1,20);  
$subject  =  '{*}';  
$result  =  str_replace($search,  $replace,  $subject);  
?>  

could  be  an  array  of  elements  "{1}",  "{2}",  "{3}"  ....  In  other  words  it  would  have  the  same  effect  as  

<?php  
$search  =  '*';  
$replace  =  range(1,20);  
$subject  =  '{*}';  
$result  =  array();  
foreach($replace  as  $r)  {  
      $result[]  =  str_replace($search,  $r,  $subject);  
}  
?>  

I  leave  more  elaborate  applications  to  your  imagination  :)  

The  result  of  a  str_replace(string,array,array)  would  therefore  presumably  be  an  array  of  arrays,  with  its  dimensions  indexed  by  the  two  arrays  passed  in.  But  then  there's  the  question  of  which  is  the  first  dimension  and  which  is  the  second.  
chirag  at  chime  dot  tv
23-Mar-2003  05:35  
All  the  Google-like  highlight  functions  above  mess  up  when  the  needle  is  within  the  url  too.  getHTMLHighlight  function  below  works  fine:  

<?php  
function  getHTMLHighlight($needle,  $haystack,  $hlS,  $hlE)  
{  
      $parts  =  explode(">",  $haystack);  
      foreach($parts  as  $key=>$part)  
      {  
          $pL  =  "";  
              $pR  =  "";  

          if(($pos  =  strpos($part,  "<"))  ===  false)  
              $pL  =  $part;  
          elseif($pos  >  0)  
          {  
              $pL  =  substr($part,  0,  $pos);  
              $pR  =  substr($part,  $pos,  strlen($part));  
          }  
          if($pL  !=  "")  
              $parts[$key]  =  preg_replace('|\b('.quotemeta($needle).')\b|iU',  $hlS.'\\1'.$hlE,  $pL)  .  $pR;  
      }  
      return(implode(">",  $parts));  
}  
?>  

Usage:  

getHTMLHighlight($needle,  $haystack,  "<b  style=\"background-color:#FF3145\">",  "</b>");  
mv@anywhere  dot  br
13-Feb-2003  11:03  
how  to  remove  accents  from  text  

<?php  
function  accents($text)  {  
      global  $export;  
      $search    =  array  ('&#31228;/span>,  '&#6652;/span>,  '&#39420;/span>,  '&#55804;/span>,  '&#950063;span>,  '?pan>,  '&#14844;/span>,  '?span>,  '&#10748;/span>,  '&#43516;/span>,  '&#59900;/span>,  '?span>,  '?pan>);  
      $replace  =  array  ('c',  'a',  'e',  'i',  'o',  'u',  'a',  'o',  'a',  'e',  'i',  'o',  'u');  
      $export        =  str_replace($search,  $replace,  $text);  
      return  $export;  
}  

accents("Carnaval  &#38963;&#920495;  Brasil");  
?>  
rit  at  NOSPAMchatol  dot  com
07-Jan-2003  09:32  
I  was  trying  to  remove  newlines  from  a  textarea  input  (result  of  failed  submission  of  parent  form  -  JS  verification  not  possible  in  this  situation)  to  send  back  to  the  textarea  via  javascript  (due  to  the  fact  that  setting  the  value  in  the  textarea  tag  does  not  work)  and  had  a  hard  time  figuring  it  out.  

If  anyone  cares,  try  replacing:  "%0D%0A"  which  is  how  I  found  it(changed  my  POST  method  to  GET)  and  tracked  it  down  in  the  address  bar  of  my  browser.  Hope  this  helps,  I  sure  wish  someone  else  had  posted  it  earlier!  
Shane43  at  aol  dot  com
17-Oct-2002  11:12  
Keep  in  mind  that  if  you  are  trying  to  remove  all  the  newlines  (\n)  from  a  fields  that  was  submitted  in  a  form,  you  may  need  look  for  \r\n  instead:  

If  this  doesn't  work:  
$text=str_replace  ("\n",  "  ",  $text);  

then  try  this:  
$text=str_replace  ("\r\n",  "  ",  $text);  
art  at  zollerwagner  dot  com
10-Oct-2002  07:26  
To  use  one  or  two  arrays  in  str_replace,  

this  appears  to  be  the  correct  format:
<?php
str_replace(array('1st_current_needle_element',  '2nd,  '3rd'),  array('1st_new_needle_element',  '2nd',  '3rd'),  $haystack)
?>

Example  of  a  single  array,  which  simply  removes  the  characters  in  the  first  array:
<?php
$text=str_replace(array('<',  '>',  '\\',  '/',  '='),  "",  $text);
?>

This  will  delete  the  chars:  <  >  \  /  =

It  could  also  be  done  by  first  defining  the  array(s),  like  this:
<?php
$targetChars=array('<',  '>',  '\\',  '/',  '=');
$text=str_replace($targetChars,  "",  $text);
?>
gwkeeper  at  mmhk  dot  cz
01-Oct-2002  03:47  
Hi,  if  You  want  to  use  case  insensitive  replacement  with  support  eastern  languages  e.g.  czech  special  chars  try  this:  

<?php  
$text  =  eregi_replace  (  (sql_regcase($searched_text)),  "<span  class=\"Marked_1\"  >\\0</span>",  $text  );  
?>  

without  sql_regcase  it  did  not  found  some  special  eastern  chars  
paul  at  atomicrevs  dot  net
28-Aug-2002  11:29  
I  made  this  to  parse  values  returned  in  a  form,  but  to  preserve  formatting  so  that  it  doesn't  get  removed  in  the  "remove  anything  but  alphanumeric"  line...    Probably  not  elegant,  but  it  works.  

<?php  
foreach  ($_POST  as  $key  =>  $val)  
    {  
      $val  =  preg_replace("(\r\n|\n|\r)",  "#",  $val);  
      $val  =  preg_replace("/[^0-9a-z  -#]/i",'',  $val);  //  strip  anything  we  don't  want  
      $val  =  str_replace("#",  "*",  $val);  //  *  Put  a  p  or  br  here.  
      $_POST[$key]  =  $val;  
    }  
?>  
unleadedis  at  optusnet  dot  com  dot  au  dot  nospam
12-Aug-2002  04:48  
The  problem  is  that  str_replace  seems  to  call  the  replace  even  though  there  may  not  be  a  replacement.  

This  is  a  problem  in  that  in  my  parsing  script  when  it  finds  a  certain  tag  it  calls  a  function,  this  function  does  a  few  SQL  queries.  It  has  been  noticed  that  doing  a  str_replace  on  a  page  that  contains  no  'tag'  that  I  am  searching  for,  the  function  is  called  anyway!!!  

To  get  around  this  I  have  to  do  a  str_pos  to  see  if  it  exists  then  call  str_replace.  

eg,  
<?php  
//  Breadcrumb  trail  (same  as  per  sitemap)  
$bc_pos  =  strpos($string,"[[breadcrumbtrail]]");  
if  ($bc_pos  ||  is_numeric($bc_pos))  {  //  true  ?  then  exectue!  
      $string  =  str_replace  ("[[breadcrumbtrail]]",  
                  generate_breadcrumb($nodedata_arr,  $db),  $string);  
}  
?>  
tapken  at  engter  dot  de
25-May-2002  07:34  
If  you  want  to  replace  only  the  first  occurence  of  a  string  you  can  use  this  function:  

<?php  
function  str_replace_once($needle,  $replace,  $haystack)  {  
      //  Looks  for  the  first  occurence  of  $needle  in  $haystack  
      //  and  replaces  it  with  $replace.  
      $pos  =  strpos($haystack,  $needle);  
      if  ($pos  ===  false)  {  
              //  Nothing  found  
              return  $haystack;  
      }  
      return  substr_replace($haystack,  $replace,  $pos,  strlen($needle));  
}  
?>  
dpardo  at  fia  dot  es
04-Apr-2002  05:03  
If  you  are  working  with  spanish  characters  and  you  are  using  accent  (marks,quotes)  you  have  to  use  something  similar  to  this  

$q  =  str_replace("&aacute;",  "a",  $q);  

4914 view

4.0 stars