I have many posts and I want to add some special offer in the ones that I post this year.
offer name - July 20, 2015
offer name - July 20, 2016
offer name - July 20, 2017
...
I'm doing this:
$a = "offer name - July 20, 2000";
if (preg_match('/2017/',$a)) {
echo 'offer';
}
it is working for 2017, but I want to add offers in posts from 2017 and next years... 18, 19. any ideas?
This variant iterates over the input and filters by year:
<?php
$input = [
'offer name - July 20, 2015',
'offer name - July 20, 2016',
'offer name - July 20, 2017'
];
$output = [];
array_walk($input, function($entry) use (&$output){
if ( preg_match('| - \w+\s+\d+,\s+(\d+)$|', $entry, $tokens)
&& intval($tokens[1]) >= 2017 ) {
$output[] = $entry;
}
});
print_r($output);
This is a somewhat more compact variant:
<?php
$input = [
'offer name - July 20, 2015',
'offer name - July 20, 2016',
'offer name - July 20, 2017'
];
$output = array_filter($input, function($entry){
return
preg_match('| - \w+\s+\d+,\s+(\d+)$|', $entry, $tokens)
&& (intval($tokens[1]) >= 2017);
});
print_r($output);
The output obviously is:
Array
(
[0] => offer name - July 20, 2017
)
you can use something like that
function isYearAllowed($date, array $allowedYears)
{
try {
$date = new \DateTime($date);
} catch (\Exception $e) {
return false;
}
if(in_array($date->format("Y"), $allowedYears)){
return true;
}else{
return false;
}
}
Example of usage
$allowedYears = ['2017','2016'];
if(isYearAllowed("2016-12-31", $allowedYears)){
echo "offer";
}else{
echo "don't offer";
}
exit;
live demo (https://eval.in/835914)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With