Replace only the first string occurence

This PHP functon will replace only the first string occurrence in a given text. This is an alternative for the preg_replace() function.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<?

 

function str_replace_first($string ,$search , $replace) {

 

if ((($string_len=strlen($string))==0) || (($search_len=strlen($search))==0)) return $string;

$pos=strpos($string,$search);

if ($pos>0) return substr($string,0,$pos).$replace.substr($string,$pos+$search_len,max(0,$string_len-($pos+$search_len)));

return $string;

}

 

//Usage example

 

$text="I love apples. I love bananas.";

echo str_replace_first($text,"love","don't love");

 

//The result

//I don't love apples. I love bananas.

?>

Newsletter

Sign up for inspiration, news and updates