PHP Code

Find a string within a string in PHP

The PHP function strrpos is great for finding the positiong of a specific character within a string. But that's exactly the problem: that it really only can search for a character. So, digging around the PHP manual, I was able to drum up this handy function, which enables you to search for entire strings, rather than individual characters. This is a recursive function, and is quite efficient.

//Find last occurance of needle in haystack
function str_rpos($haystack, $needle, $start = 0){
   $tempPos = strpos($haystack, $needle, $start);
   if($tempPos === false){
       if($start == 0){
           //Needle not in string at all
           return false;
           //No more occurances found
           return $start - strlen($needle);
       //Find the next occurance
       return str_rpos($haystack, $needle, $tempPos + strlen($needle));

Leave a Reply

Your email address will not be published. Required fields are marked *

To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image