DarkWater Posted May 4, 2008 Share Posted May 4, 2008 Is there a simple way to do this? Like, a built-in PHP function? I couldn't find one in the manual, so I wrote one, but I really wish there was a better way: <?php function find_occurences($string, $find) { if (strpos(strtolower($string), strtolower($find)) !== FALSE) { $pos = -1; for ($i=0; $i<substr_count(strtolower($string), strtolower($find)); $i++) { $pos = strpos(strtolower($string), strtolower($find), $pos+1); $positionarray[] = $pos; } return $positionarray; } else { return FALSE; } } ?> Anyone? Link to comment Share on other sites More sharing options...
rarebit Posted May 4, 2008 Share Posted May 4, 2008 Not that I can think of but depending upon what you want to do you could look at preg_split or preg_replace Link to comment Share on other sites More sharing options...
Rohan Shenoy Posted May 4, 2008 Share Posted May 4, 2008 I am thinking of something, I will test the code and put it here. Gimme some time. Link to comment Share on other sites More sharing options...
Rohan Shenoy Posted May 4, 2008 Share Posted May 4, 2008 *EDIT: Sorry, need to fix some things in the code. Will post it again. Link to comment Share on other sites More sharing options...
Rohan Shenoy Posted May 4, 2008 Share Posted May 4, 2008 I am sorry about the length of the code being longer than yours but right now, this is what I cud think off. <?php $string="This is my house. this is my living room. This is my bedroom. This is great!"; $delimiter="This"; $pos=array(); function fao($str,$delim) //fao stands for Find All Occurences { $str_bits=explode(strtolower($delim),strtolower($str)); global $pos; $local_pos=array(); $counter="-1"; foreach($str_bits as $individual_bit) { $local_pos[]=$individual_bit; if(sizeof($local_pos)>1) { $local_pos_length=strlen(implode("",$local_pos))+strlen($delim)+(4*$counter); } else { $local_pos_length=strlen(implode("",$local_pos)); } $counter++; $pos[]=$local_pos_length; } global $string; } fao($string,$delimiter); $size=sizeof($pos)-1; echo "Occurunces were found to start at the following positions(Left most character is considered as at position 0):<br>"; for($i=0; $i<$size; $i++) { echo $pos[$i]."<br>"; } ?> Link to comment Share on other sites More sharing options...
rarebit Posted May 4, 2008 Share Posted May 4, 2008 DarkWater's code is faster and more efficient! Link to comment Share on other sites More sharing options...
Sovetryne Posted December 3, 2012 Share Posted December 3, 2012 DarkWater has written a working function - Rohan Shenoy's procedure doesn't work correctly, unless you add following at the beginning of the loop in the bottom of the code: if ($i>1) { $pos[$i] = $pos[$i]-(1*$i)+1; } //Sovetryne Link to comment Share on other sites More sharing options...
Philip Posted December 3, 2012 Share Posted December 3, 2012 Please don't necro 4 year old threads... Link to comment Share on other sites More sharing options...
Recommended Posts