PHP匹配出现次数

时间:2018-03-12 10:34:17

标签: php

我有这个PHP字符串:

$range = "['2018-03-17','2018-03-19','2018-03-18','2018-03-18']";

我想循环遍历整个字符串,并执行类似..

的操作
if day == "Saturday" || day == "Sunday" and only one occurrence of this in string then { // Do something } else { // Do something else }

我用正则表达式[0-9] {4} - [0-9] {2} - [0-9] {2}探索了preg_match_all但是我无法理解它,任何帮助真的很感激。

3 个答案:

答案 0 :(得分:0)

试试这段代码。

 if (day == "Saturday" || day == "Sunday" && (substr_count($range,"2018-03-18")) == 1 ){ 
// Do something 
} else { 
// Do something else 
}

substr_count($ range," 2018-03-18")将在此处返回2。 substr_count返回主字符串中子字符串的出现次数。

希望它有所帮助。

感谢。

答案 1 :(得分:0)

首先,您需要将字符串解码为数组:

$range = json_decode('["2018-03-17","2018-03-19","2018-03-18","2018-03-18"]');

然后循环:

$rangeCount = array_count_values($range);
forearch ($range as $d) {
    $date = new DateTime($d);
    $weekDay = (int) $date->format('N');
    $found = $rangeCount[$d];

    if ($weekDay === 6 || $weekDay === 7 && $found === 1) {
        // here is your code
    }
}

我还没有测试过代码。

答案 2 :(得分:0)

试试这个

    <?php
    $range_string = '["2018-03-17","2018-03-19","2018-03-18","2018-03-18"]';
    $range = json_decode($range_string);

    foreach($range as $date){
     $nameOfDay = date('l', strtotime($date));
     if (($nameOfDay == 'Saturday' || $nameOfDay =='Sunday') && count(array_keys($range, $date)) == 1) 
     {
        echo "$nameOfDay exits only once on $date"."<br/>";
     }else{
        echo "$nameOfDay exits multiple time on $date"."<br/>";
     }
}
    ?>

<强>输出

Saturday exits only once on 2018-03-17
Monday exits multiple time on 2018-03-19
Sunday exits multiple time on 2018-03-18
Sunday exits multiple time on 2018-03-18

演示: https://eval.in/970622