View Full Version : StrPos - Finding Substring within a String Question

10-10-2007, 02:10 PM
Hi again,
I just wanted to know how to find every occurrence of a sub-string in a string?

I would like to find the positions of every occurrence of a word within a sentence.

CodingForums is a web code and development forum
In the above sentence, I would like to have an array with the positions of all occurences of the letters "or" (2 occurrences in this case). I'm sure strpos can do this, can any one provide a function or the code necessary to do this?

Thanks :thumbsup:

10-10-2007, 03:21 PM
maybe I need to explain a bit, I just want to search a string and get the position of each occurrence of a string. With strpos you only get the first occurrence - and I'd like to get it for all of them.

10-10-2007, 03:27 PM
function findAllOccurences($Haystack, $needle, $limit=0)
$Positions = array();
$currentOffset = 0;
while(($pos = strpos($Haystack, $needle, $offset))!==false && ($count < $limit || $limit == 0))
$Positions[] = $pos;
$offset = $pos + strlen($needle);
return $Positions;

I cant take credit for this it is from the user contributed notes in the PHP function manual entry for STRPOS


This is a great place to start when your stuck with something.

10-10-2007, 03:34 PM
I wrote a function just to test my rusty skills. (I work in a travel agency now). I really like the function posted before mine. But seeing as I wrote this I'll give it to you anyway.

$full_string = "Hello there bobby dog. You rolling with the big boys now."; //string to be searched through.
$counter = 0; $x = 0;//misc counters.
$search_val = "he"; //string to search for
$search_length = strlen($full_string);//get the length of the string
$search_val_length = strlen($search_val);//get the length of the string to search for.
$test = strpos($full_string,$search_val);
$first_letter = $search_val{0};
if ($test){
while ($counter < $search_length){
if (strtolower($full_string{$counter}) === $first_letter){
if ((strtolower(substr($full_string,$counter,$search_val_length)) == $search_val)){
$occurences[$x] = $counter . "-" . ($counter + $search_val_length - 1);
$counter = $counter + $search_val_length - 1;
} else{ echo("No occurences"); }

its lame, but was interesting (&challenging to some extent)...