Checking for multiple strpos values

后端 未结 7 1924
陌清茗
陌清茗 2021-01-05 05:51

I am wondering how to complete multiple strpos checks.

Let me clarify:
I want strpos to check the variable \"COLOR\" to see if any numbers fro

相关标签:
7条回答
  • 2021-01-05 06:51

    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>";         
        }       
      }
    
    0 讨论(0)
提交回复
热议问题