Which is the best way to do the following ?
# if I have the following string :
$str = "Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar";
# and I want to remove "o" character after 5-th match so result I need is :
$newStr = "Foo Bar Foo Bar Fo Bar F Bar F Bar F Bar F Bar...";
The way I know :
$str = "Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar";
$str = explode("o", $str);
$new = "";
$c = 1;
foreach($str as $k) {
if($c>5)
$new .= $k;
else
$new .= $k."o";
$c++;
}
I believe there is a better way of doing this.
There must be a million ways to do this. I had a quick scan through the built-in functions to see if there was a
strposwith an nth occurance, but there was not.Here is a solution. It might not be the best, but who knows.
Sorry for the mad for loop, been doing too much code golf lately!
Here’s another way to do it.