September 29th, 2006

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.

<?php
//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;
       }else{
           //No more occurances found
           return $start - strlen($needle);
       }
   }else{
       //Find the next occurance
       return str_rpos($haystack, $needle, $tempPos + strlen($needle));
   }
}
?>

Leave a reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image