Finding mulitple occurences of a string withing another


/ Published in: PHP
Save to your folder(s)

I wrote this method just to find multiple occurences of a substring withing another and return indexed-positions that matched in an array.


Copy this code and paste it in your HTML
  1. function multipleSubstringOccurences($string,$substring)
  2. {
  3. $string=strtolower($string);
  4. $substring=strtolower($substring);
  5. $matched_positions=array();
  6. $sample_string_to_be_matched=$string;
  7. $string_to_be_found=$substring;
  8. $strlen_string_to_be_found=strlen($string_to_be_found);
  9. $matched_positions[]=strpos($sample_string_to_be_matched,$string_to_be_found);
  10.  
  11. if(strpos($sample_string_to_be_matched,$string_to_be_found))
  12. {
  13. $current_array_index=0;
  14. $cur_pos=strpos($sample_string_to_be_matched,$string_to_be_found)+$strlen_string_to_be_found;
  15. $still_finding=true;
  16. while($still_finding)
  17. {
  18. $sample_string_to_be_matched=substr($sample_string_to_be_matched,$cur_pos,strlen($sample_string_to_be_matched));
  19. if(strpos($sample_string_to_be_matched,$string_to_be_found))
  20. {
  21. $still_finding=true;
  22. $cur_pos=strpos($sample_string_to_be_matched,$string_to_be_found)+$strlen_string_to_be_found;
  23. $matched_positions[]=$matched_positions[$current_array_index]+strpos($sample_string_to_be_matched,$string_to_be_found)+$strlen_string_to_be_found;
  24. $current_array_index++;
  25. }
  26. else
  27. {
  28. $still_finding=false;
  29. }
  30.  
  31.  
  32. }
  33. }
  34. else
  35. {
  36. return false;
  37. }
  38.  
  39. return $matched_positions;
  40.  
  41. }
  42.  
  43. //Usage
  44.  
  45. $string_main="Life is sometimes hard. Sometimes it's delightful.";
  46. $string_to_find="Sometimes";
  47. $res_array=array();
  48. $res_array=multipleSubstringOccurences($string_main,$string_to_find);
  49.  
  50. /*
  51.  
  52. Will return an array with all starting indexes of string "sometimes".
  53.  
  54. */

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.