Advertisement
nucklear

PHP replace n string

Jun 12th, 2012
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.64 KB | None | 0 0
  1. function str_replace_count($search,$replace,$subject,$times) {
  2.     $subject_original=$subject;
  3.     $len=strlen($search);    
  4.     $pos=0;
  5.     for ($i=1;$i<=$times;$i++) {
  6.         $pos=strpos($subject,$search,$pos);
  7.         if($pos!==false) {                
  8.             $subject=substr($subject_original,0,$pos);
  9.             $subject.=$replace;
  10.             $subject.=substr($subject_original,$pos+$len);
  11.             $subject_original=$subject;
  12.         } else {
  13.             break;
  14.         }
  15.     }
  16.     return($subject);
  17. }
  18. ?>
  19.  
  20.  
  21.  
  22. To use it, just call the function, like this:
  23. $myString = "X. Xavier Reynolds";
  24. print str_replace_count("X","A",$myString,1);
  25. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement