All occurences
Easiest is to replace all occurrences. Just use str_replace
on your string
$str = 'stackoverflow site is best site';
$str = str_replace('site', 'website', $str);
Live example
First occurence
To replace single instances (like the first, or second, or etc), you can use substr_replace
which allows you to replace a certain character range with text. You have to find that range first though. You can use strpos
for that.
$str = 'stackoverflow site is best site';
$search = 'site';
$start = strpos($str, $search);
$str = substr_replace($str, 'website', $start, strlen($search));
Live example
Any specific occurence
Now extending on the previous code to replace the second or third instances, you need to subsequently call strpos
and feed it the offset of the previous result. Here is a simple way to do it with a for
loop.
$str = 'stackoverflow site is best site';
$search = 'site';
$count = 2;
$start = strpos($str, $search);
for($i = 0; $i < $count - 1; $i++)
$start = strpos($str, $search, $start + 1);
$str = substr_replace($str, 'website', $start, strlen($search));
Live example
I am using a $count
variable to determine what word I want to replace.