检查多个strpos值

Cha*_*iff 5 php strpos

我想知道如何完成多个strpos检查.

让我澄清一下:
我想要strpos来检查变量"COLOR"以查看变量中是否存在1到8之间的任何数字.如果存在从1到8的任何数字,我想回显"已选择".

例子:
比方说,只有数字1是变量,它 "选择"呼应.
比方说,数字1 2和3是在变量,它回声"选择".
比方说,数字3 9月25日都在变,这回声"选择"(因为那3!).
假设只有数字9在变量中,它不会回显.
假设数字9 25 48在变量中,它不会回显.

Cha*_*iff 12

我刚刚使用了OR语句(||)

<?php 
  if (strpos($color,'1') || strpos($color,'2') || strpos($color,'3') || strpos($color,'4') || strpos($color,'5') || strpos($color,'6') || strpos($color,'7') || strpos($color,'8') === true) 
   {
    //do nothing
   } else { 
            echo "checked"; 
          } 
?>
Run Code Online (Sandbox Code Playgroud)

  • `strpos()`返回字符串中针存在的位置,因此如果这些数字中的任何一个位于第一个位置,它将返回"0"并且您的代码将因为您正在进行布尔检查而失败.此外,`strpos()`永远不会返回布尔值TRUE,因此检查`=== true`是不正确的. (3认同)

小智 8

我发现上面的答案不完整,并提出了我自己的功能:

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

用法:

$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>";         
    }       
  }
Run Code Online (Sandbox Code Playgroud)


小智 7

尝试preg匹配多个

if (preg_match('/word|word2/i', $str))
Run Code Online (Sandbox Code Playgroud)

strpos()有多针?