Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an array as needles in strpos

Tags:

arrays

php

strpos

How do you use the strpos for an array of needles when searching a string? For example:

$find_letters = array('a', 'c', 'd'); $string = 'abcdefg';  if(strpos($string, $find_letters) !== false) {     echo 'All the letters are found in the string!'; } 

Because when using this, it wouldn't work, it would be good if there was something like this

like image 646
MacMac Avatar asked Jun 08 '11 20:06

MacMac


People also ask

What is the strpos () function used for?

strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.

What does Strpos return if not found?

Returns the position of the first occurrence of a string inside another string, or FALSE if the string is not found.

Is PHP an array?

Definition and Usage. The is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.


1 Answers

@Dave an updated snippet from http://www.php.net/manual/en/function.strpos.php#107351

function strposa($haystack, $needles=array(), $offset=0) {         $chr = array();         foreach($needles as $needle) {                 $res = strpos($haystack, $needle, $offset);                 if ($res !== false) $chr[$needle] = $res;         }         if(empty($chr)) return false;         return min($chr); } 

How to use:

$string = 'Whis string contains word "cheese" and "tea".'; $array  = array('burger', 'melon', 'cheese', 'milk');  if (strposa($string, $array, 1)) {     echo 'true'; } else {     echo 'false'; } 

will return true, because of array "cheese".

Update: Improved code with stop when the first of the needles is found:

function strposa(string $haystack, array $needles, int $offset = 0): bool  {     foreach($needles as $needle) {         if(strpos($haystack, $query, $offset) !== false) {             return true; // stop on first true result         }     }      return false; } $string = 'This string contains word "cheese" and "tea".'; $array  = ['burger', 'melon', 'cheese', 'milk']; var_dump(strposa($string, $array)); // will return true, since "cheese" has been found 
like image 136
Binyamin Avatar answered Oct 01 '22 04:10

Binyamin