Define multiple needles using stripos

2019-06-05 08:37发布

How can i define multiple needles and still perform the same actions below. Im trying to define extra keywords such as numbers, numerals, etc... as of now i have to create a duplicate if loop with the minor keyword change.

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);
}

标签: php strpos
3条回答
放荡不羁爱自由
2楼-- · 2019-06-05 08:51

Create a function that loops through an array?

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 added semicolon

查看更多
小情绪 Triste *
3楼-- · 2019-06-05 09:05
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);
}

Usage:

$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';
}

function taken from https://stackoverflow.com/a/9220624/1018682

查看更多
Explosion°爆炸
4楼-- · 2019-06-05 09:05

Though the previous answers are correct, but I'd like to add all the possible combinations, like you can pass the needle as array or string or integer.
To do that, you can use the following snippet.

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;
}

You can now use the second parameter as array or string or integer, whatever you want.

查看更多
登录 后发表回答