Replace Once

str_replace is a great function for finding words and replacing them with a chunk of text. However, I was seeking to find just one instance of a word and replace it. I knew that there are more instances but I just need to change one.

To this end, after lots of searching, I found this snippet on surprise surprise - the php manual. Full credit as far as I can tell goes to xinobit at gmail dot com. Hope this helps someone.


<?php
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);
 
}
/* Example usage */
$w="abracadabra";
print 
str_replace_count("abra","----",$w,2);
?>

Comments

Should be called replace as many times as you want

... but for my initial usage I was just replacing once.

Hope it helps someone out there though :)

Br

Jamie

Unraveling the mysteries of the web
http://www.skiffie.com

Syndicate content