How to replace one occurrence of a word with PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lovelf
Forum Contributor
Posts: 153
Joined: Wed Nov 05, 2008 12:06 am

How to replace one occurrence of a word with PHP

Post by lovelf »

example: $var1='hellowordinghellowording';
I want to replace hello just once not twice inside this variable
lovelf
Forum Contributor
Posts: 153
Joined: Wed Nov 05, 2008 12:06 am

Re: How to replace one occurrence of a word with PHP

Post by lovelf »

Code: Select all

    function str_replace_once($str_pattern, $str_replacement, $string){ 
        
        if (strpos($string, $str_pattern) !== false){ 
            $occurrence = strpos($string, $str_pattern); 
            return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern)); 
        } 
        
        return $string; 
    } 
I have that function to replace once, now what to replace more than once, a given number of times, taken by the count parameter of the str_replace function, to replace all occurrences but one.
lovelf
Forum Contributor
Posts: 153
Joined: Wed Nov 05, 2008 12:06 am

Re: How to replace one occurrence of a word with PHP

Post by lovelf »

Got it, with a loop
Post Reply