2014-09-27 00:29
浏览 59


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

$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]
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanbi3151 2014-09-27 00:34

    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:


    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.

    打赏 评论
  • donglaogu3788 2014-09-27 00:51

    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');
    打赏 评论
  • douba4824 2014-09-27 00:52

    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:

    打赏 评论

相关推荐 更多相似问题