Replacing a needle in a haystack with a straw?



I'm stuck again on something which ought to be really easy. But, having soent an hour perusing the manual, I'm not closer to the answer.

Here's the problem (simplified).

I have a string which will always include a number of colon ":" characters. I want to replace the last colon in the string with a string. For example "straw".

$haystack = "Here is a string with : some : colons : in it"

$pos = strripos($haystack, ":");

Now I know the position of the last colon in $haystack.

So how do I replace that colon with "straw"?

$haystack = "Here is a string with : some : colons straw in it"

Thanks in advance. I know I'm going to kick myself! :oops:

The tricky part here is that unlike some string functions, str_replace() doesn't accept a starting index. So it'll do the whole string no matter what (meaning it would replace every instance of your needle). My solution would be to handle it in chunks. Since you know the index (counting from 0) of the last needle, you can treat everything after that as a separate string and just do the str_replace() on that:

$haystack = 'Here is a string with : some : colons : in it';
$needle = ':';
$replace = 'straw';
$last_needle_index = strrpos($haystack, $needle);

$string = substr($haystack, 0, $last_needle_index) .
             substr($haystack, $last_needle_index)

echo $string;

So, to explain, the first substr() describes everything before the last occurrance of $needle, which I then concatenate with everything after (inclusive) the last occurrence of $needle, replacing every occurrence of $needle with $replace in the latter part.
Understood. I'd figured out something similar but I thought there would be a more elegant method!

Most grateful for your time. I'll continue with my labours. The real "haystack" is actually in the middle of an array but I'll figure it out from here. :)