Define multiple needles using stripos

倾然丶 夕夏残阳落幕 提交于 2020-01-03 02:42:07

问题


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

回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/5726425/define-multiple-needles-using-stripos

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!