使用Stripos定义多针

| 我如何定义多个针头并仍然执行以下相同操作。我试图定义额外的关键字,例如数字,数字等。截至目前,我必须使用次要关键字更改来创建重复的if循环。
if (stripos($data, \'digits\') !== false) {
$arr = explode(\'+\', $data);

for ($i = 1; $i < count($arr); $i += 2) {
    $arr[$i] = preg_replace(\'/\\d/\', \'\', $arr[$i]);
}

$data = implode(\'+\', $arr);
}
已邀请:
创建一个遍历数组的函数?
function check_matches ($data, $array_of_needles)
{
   foreach ($array_of_needles as $needle)
   {
        if (stripos($data, $needle)!==FALSE)
        {
             return true;
        }
   }

   return false;
}

if (check_matches($data, $array_of_needles))
{
   //do the rest of your stuff
}
--edit添加分号
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);
}
用法:
$array  = array(\'1\',\'2\',\'3\',\'etc\');

if (strposa($data, $array)) {
  $arr = explode(\'+\', $data);

  for ($i = 1; $i < count($arr); $i += 2) {
    $arr[$i] = preg_replace(\'/\\d/\', \'\', $arr[$i]);
  }

  $data = implode(\'+\', $arr);

} else {
  echo \'false\';
}
函数取自https://stackoverflow.com/a/9220624/1018682
尽管前面的答案是正确的,但是我想添加所有可能的组合,例如可以将指针作为数组或字符串或整数传递。 为此,您可以使用以下代码段。
function strposAll($haystack, $needles){
    if(!is_array($needle)) $needles = array($needles); // if the $needle is not an array, then put it in an array
    foreach($needles as $needle)
        if( strpos($haystack, $needle) !== False ) return true;
    return false;
}
现在,您可以根据需要使用第二个参数作为数组,字符串或整数。

要回复问题请先登录注册