0

i need to find the all positions of a particular character in a string. I am using the following code

$pos = 0;
 $positions = array();
 while( $pos = strpos($haystack,$needle,$pos){      
    $positions[] = $pos;
    $pos = $pos+1;  
 }

the problem with this code is that when the needle is at location 1,its returns 1 and so doesn't enter the loop.

So i tried the following

     $pos = 0;
     $positions = array();
     while( ($pos = strpos($haystack,$needle,$pos) || (strpos($haystack,$needle,$pos)=== 0){        
        $positions[] = $pos;
        $pos = $pos+1;  
     }

and,

     $pos = 0;
     $positions = array();
     while( ($pos = strpos($haystack,$needle,$pos) || (strpos($haystack,$needle,$pos) != false){        
        $positions[] = $pos;
        $pos = $pos+1;  
     }

But nothing seems to be working. Is there any other way.

The two alternative i tried give me

Allowed memory size of 268435456 bytes exhausted

which i think has more to do with programming error than memory issue.

Plz help.

Mayur Buragohain
  • 1,566
  • 1
  • 22
  • 42
  • possible duplicate of [PHP Find all occurrences of a substring in a string](http://stackoverflow.com/questions/15737408/php-find-all-occurrences-of-a-substring-in-a-string) – N.B. Sep 23 '13 at 11:00

2 Answers2

2

You need to use !== instead of != because zero is considered false so you need to compare by type as well:

while($pos = (strpos($haystack,$needle,$pos) !== false){
    $positions[] = $pos;
    $pos++;
}

Edit

See the working version of your code from the comment:

$positions = array(); 
while( ($pos = strpos('lowly','l',$pos)) !== false){
    $positions[] = $pos; 
    $pos++; 
} 
print_r($positions);

See it working here.

Shomz
  • 37,421
  • 4
  • 57
  • 85
-1

Use this code..

$start = 0;
while ($pos = strpos($string, ',', $start) !== FALSE) {
 $count++;
 $start = $pos + 1;

}