[英]PHP Matching number of occurrences
I have this PHP string : 我有这个PHP字符串:
$range = "['2018-03-17','2018-03-19','2018-03-18','2018-03-18']";
I'm wanting to loop through the entire string, and do something like.. 我想遍历整个字符串,并做类似的事情。
if day == "Saturday" || day == "Sunday" and only one occurrence of this in string then { // Do something } else { // Do something else }
I've explored preg_match_all with a regex [0-9]{4}-[0-9]{2}-[0-9]{2} but I can't get my head around it, any help would be really appreciated. 我已经使用正则表达式[0-9] {4}-[0-9] {2}-[0-9] {2}探索了preg_match_all,但是我无法理解,任何帮助都是真的赞赏。
Try this code. 试试这个代码。
if (day == "Saturday" || day == "Sunday" && (substr_count($range,"2018-03-18")) == 1 ){
// Do something
} else {
// Do something else
}
substr_count($range,"2018-03-18") will return 2 here. substr_count($ range,“ 2018-03-18”)将在此处返回2。 substr_count return the number of occurrence of a sub string in main string.
substr_count返回主字符串中子字符串出现的次数。
Hope it helps. 希望能帮助到你。
Thanks. 谢谢。
First, you need to decode your string to array: 首先,您需要将字符串解码为数组:
$range = json_decode('["2018-03-17","2018-03-19","2018-03-18","2018-03-18"]');
And then loop: 然后循环:
$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
}
}
I haven't tested the code. 我还没有测试代码。
Try like this 这样尝试
<?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/>";
}
}
?>
Output 产量
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
Demo : https://eval.in/970622 演示: https : //eval.in/970622
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.