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);
}
Ryan Cooper
  • 703
  • 3
  • 11
  • 23

3 Answers3

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

Jacer Omri
  • 1,723
  • 22
  • 37
Dormouse
  • 5,130
  • 1
  • 26
  • 42
  • @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. – Ryan Cooper Apr 20 '11 at 07:14
  • I've messed around with the loops but im afraid ill exclude something... If you have any ideas let me know. – Ryan Cooper Apr 20 '11 at 07:44
  • @Ryan/@Ben, you're just missing a semi-colon after the `return true`. – Nick Apr 20 '11 at 13:31
  • @Nick 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. – Ryan Cooper Apr 20 '11 at 16:08
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://stackoverflow.com/a/9220624/1018682

Community
  • 1
  • 1
Ben Miller
  • 29
  • 7
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.

ssi-anik
  • 2,998
  • 3
  • 23
  • 52