Checking for multiple strpos values

I found the above answers incomplete and came up with my own function:

/**
 * Multi string position detection. Returns the first position of $check found in 
 * $str or an associative array of all found positions if $getResults is enabled. 
 * 
 * Always returns boolean false if no matches are found.
 *
 * @param   string         $str         The string to search
 * @param   string|array   $check       String literal / array of strings to check 
 * @param   boolean        $getResults  Return associative array of positions?
 * @return  boolean|int|array           False if no matches, int|array otherwise
 */
function multi_strpos($string, $check, $getResults = false)
{
  $result = array();
  $check = (array) $check;

  foreach ($check as $s)
  {
    $pos = strpos($string, $s);

    if ($pos !== false)
    {
      if ($getResults)
      {
        $result[$s] = $pos;
      }
      else
      {
        return $pos;          
      }
    }
  }

  return empty($result) ? false : $result;
}

Usage:

$string  = "A dog walks down the street with a mouse";
$check   = 'dog';
$checks  = ['dog', 'cat', 'mouse'];

#
# Quick first position found with single/multiple check
#

  if (false !== $pos = multi_strpos($string, $check))
  {
    echo "$check was found at position $pos<br>";
  }

  if (false !== $pos = multi_strpos($string, $checks))
  {
    echo "A match was found at position $pos<br>";
  }

#
# Multiple position found check
#

  if (is_array($found = multi_strpos($string, $checks, true)))
  {
    foreach ($found as $s => $pos)
    {
      echo "$s was found at position $pos<br>";         
    }       
  }

try preg match for multiple

if (preg_match('/word|word2/i', $str))

strpos() with multiple needles?


I just used the OR statement (||)

<?php 
  if ((strpos($color,'1') || strpos($color,'2') || strpos($color,'3')) === true) 
   {
      //do nothing
   } else { 
      echo "checked"; 
   } 
?>

Tags:

Php

Strpos