Posted By

lancemonotone on 01/27/10


Tagged

search array find substring


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

derek


substr_in_array()


 / Published in: PHP
 

URL: http://368design.com

Searches all array elements for a given substring. Returns an array of found key=>value pairs or false if not found.

  1. /**
  2.  *
  3.  * @Search for substring in an array
  4.  *
  5.  * @param string $neele
  6.  *
  7.  * @param mixed $haystack
  8.  *
  9.  * @return mixed Array or false if not found
  10.  *
  11.  */
  12. function substr_in_array($haystack, $needle)
  13. {
  14. $found = array();
  15. /*** cast to array ***/
  16. $needle = (array) $needle;
  17.  
  18. /*** map with preg_quote ***/
  19. $needle = array_map('preg_quote', $needle);
  20.  
  21. /*** loop of the array to get the search pattern ***/
  22. foreach ($needle as $pattern)
  23. {
  24. if (count($found = preg_grep("/$pattern/", $haystack)) > 0) {
  25. return $found;
  26. }
  27. }
  28. /*** if it is not found ***/
  29. return false;
  30. }

Report this snippet  

You need to login to post a comment.