Help2Go
Free Computer Help.
Powered by Volunteers.




PHP : How to replace only the first occurrence in a string with str_replace

by Oscar Sodani
June 14, 2006

Oscar Sodani is a founder of Help2Go and owner of Help2Go Networks, an IT consulting firm in the Washington D.C. area. Oscar holds the CISSP certification as well as industry certifications from Microsoft, Cisco and Novell.

PHP's str_replace function drives me crazy sometimes. It only allows you to replace ALL of the occurrences of a string. There are many times that I just want to replace the first occurrence, or the first 2 occurrences of a string.




For instance, if I had the string "X. Xavier Reynolds", and I wanted to easily replace just the first occurence of the X character, I would have to jump through hoops to split the string first to replace only the first occurrence.

Luckily, I found a great snippet function posted by xinobit on the PHP documentation web site. I include it in almost all of my PHP apps:

function str_replace_count($search,$replace,$subject,$times) {
  
$subject_original=$subject;
  
$len=strlen($search);   
 
$pos=0;
   for (
$i=1;$i<=$times;$i++) {
      
$pos=strpos($subject,$search,$pos);
       if(
$pos!==false) {               
          
$subject=substr($subject_original,0,$pos);
          
$subject.=$replace;
          
$subject.=substr($subject_original,$pos+$len);
          
$subject_original=$subject;
       } else {
           break;
       }
   }
   return(
$subject);
}
?> 

 

To use it, just call the function, like this:

$myString = "X. Xavier Reynolds";
print
str_replace_count("X","A",$myString,1);
?>

 

 



Have a question? Need help? Get free, friendly person-to-person help with your computer questions or spyware questions in our help forums!

Creative Commons License

(C) 2008 Help2Go - Contact Us