How do I find the last occurrence of a character in a string?
Actually, to speed that up, the answer is strpos.
So if you want to find the LAST occurrence, then add another 'r', and you have yourself the function of choice: strrpos - we emphasise this as you will get confused if you miss out the second 'r' so always ensure that you put it in.
Here is the function in action:
<?php
$data = "lets go backwards";
$lastr = strrpos($data,"r");
echo "The last 'r' occurs at $lastr";
//The last 'r' occurs at 14
?>
And there you have it - we know the position of the last 'r' in there.
This function is useful for a range of reasons. Sometimes we will want to trim the string so that anything after the bit we're interested in disappears.
For instance, if you want to trim a long string of text down to, say, length 100 characters, but want to stop at the last time a space occurs, then this function is really useful.
It looks a bit naff if our data ends with something like "I was just sayi..." - we want it to end with "I was just..." so we end with full words.
This can be achieved with a combination of strrpos, strlen and substr - have a go and see if you can work out how to trim any string of data down so that is a set length, but always ends with a full word - this is really useful for creating meta tags and titles for instance on your dynamic web pages, so is worth working out!
More strings PHP Questions
How do I one-way encrypt a string in PHP?How do I find the length of a string in PHP?
How can I remove trailing space from a string?
How do I reverse a string in PHP?
How do I extract the values of variables from a string?