dongxiong5546
2014-09-27 00:29
浏览 59
已采纳

如何检查字符串是否包含存储在数组中的字符,但如果字符串包含不在数组中的任何字符,则返回false

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

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:

    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.

    已采纳该答案
    打赏 评论
  • 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: http://phiddle.net/6

    打赏 评论

相关推荐 更多相似问题