Reputation: 15
$string = 'Hellow there. Hooman lives on earth. Hooman loves cats.';
Now, I want to replace the 2nd Hooman word with Human and result should be as follow:
Hellow there. Hooman lives on earth. Human loves cats.
Here's what I've done so far...:
<?php
$string = 'Hellow there. Hooman lives on earth. Hooman loves cats.';
echo preg_replace('/Hooman/', 'Human', $string, 2);
?>
But it returns: Hellow there. Human lives on earth. Human loves cats.
Upvotes: 0
Views: 773
Reputation: 23958
This code assumes there is at least one Hooman in the string.
Find the Hoomans position and substring it there and do the replace on the second part of the string.
$find = "Hooman";
$str = 'Hellow there. Hooman lives on earth. Hooman loves cats.';
$pos = strpos($str, $find);
echo substr($str, 0, $pos+strlen($find)) . str_replace($find, "Human", substr($str, $pos+strlen($find)));
Upvotes: 0
Reputation: 5683
You can use preg_replace
function str_replace_n($search, $replace, $subject, $occurrence)
{
$search = preg_quote($search);
return preg_replace("/^((?:(?:.*?$search){".--$occurrence."}.*?))$search/", "$1$replace", $subject);
}
echo str_replace_n('Hooman','Human',$string, 2);
Upvotes: 1