Garrett Blackmon
Garrett Blackmon

Reputation: 41

How can I check if a string contains characters stored in an array but return false if it contains any characters not in the array

Basically I'm checking days of the week from an array to a string based on an initialization of the day for instance:

<?php
$check_days = array("M", "T");
$days1 = "MTW";
$days2 = "M";
[insert code to compare $check_days to $days1 and $days2 so that $days1 returns FALSE while $days2 returns TRUE]
?>

Upvotes: 0

Views: 84

Answers (3)

StackSlave
StackSlave

Reputation: 10627

Try this:

function checkDays($testFor, $inString){
  $a = str_split($inString); $d = array();
  foreach($a as $v){
    if(!in_array($testFor, $v) || in_array($d, $v)){
      return false;
    }
    $d[] = $v;
  }
  return true;
}
$check_days = array('M', 'T');
echo checkDays($check_days, 'MTW');
echo checkDays($checkdays, 'M');

Upvotes: 0

Schlaus
Schlaus

Reputation: 19212

Sorry, I read your question wrong, and so my answer is wrong too. I'd go with wavemode's solution.

Original answer

If I understand your requirements correctly, you want to make sure all the days in check_days must exist in the variable to be tested. If I'm correct, this function will work:

function checkDays($haystack, $validator) {
    $ok = true;
    foreach ($validator as $day) {
        $ok = (strpos($haystack, $day) !== false) && $ok;
    }
    return $ok;
}

See it in action in this phiddle: http://phiddle.net/6

Upvotes: 0

wavemode
wavemode

Reputation: 2116

Try using a regex character class and implode:

if (preg_match('/^['.implode($check_days).']+$/', $days1)) {
    // do some stuff
}

EDIT: Let me help explain what's going on here:

implode($check_days)

This combines all the elements of an array into a single string. In your case, this is "MT".

preg_match('/^[MT]+$/', $days1);

This is a regular expression that checks that after the 'beginning' (^), $days1 contains either an "M" or a "T" ([MT]), repeated one or more times (+), then the string ends ($). It returns true if this is the case.

Hope that helps.

Upvotes: 3

Related Questions