Define multiple needles using stripos
Asked Answered
I

3

1

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);
}
Intraatomic answered 20/4, 2011 at 6:38 Comment(0)
E
3

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

Evelineevelinn answered 20/4, 2011 at 6:47 Comment(4)
@Ben Stephenson The loops look correct to me, i am new to PHP but im getting syntax error, unexpected '}', any clue why? It's unclear to me.Intraatomic
I've messed around with the loops but im afraid ill exclude something... If you have any ideas let me know.Intraatomic
@Ryan/@Ben, you're just missing a semi-colon after the return true.Peadar
@Peadar Thanks, i appreciate it i cant believe i missed that. I'm used to it throwing unexpected T_VARIABLE... now i know next time, thanks.Intraatomic
E
0
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://mcmap.net/q/194796/-using-an-array-as-needles-in-strpos-duplicate

Epagoge answered 26/8, 2013 at 20:40 Comment(0)
S
0

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.

Stratopause answered 27/12, 2014 at 21:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.