<?php $trailingString = '7mon6w5d4h3m2s bazinga!'; $leadingString = 'bazinga! in 9w8d7h6m5s'; $both = 'foo in 9d8h5m bar'; $noText = '2 w 3 m 4 d 9 mon'; /* * Replaces (s|m|h|d|w|mon) with strtotime compatible abbreviations * Optionally allows leading and/or trailing strings and returns an array with separated result set * * It should allow these and alikes: https://gist.github.com/DaveRandom/625fb4bf73112474fb5768a0a300e4e5 * * @param string $input, bool $requireLeadingString, bool $requireTrailingString * @return array $array */ function getTimeSpec(string $input, bool $requireLeadingString = false, bool $requireTrailingString = false): array { $expr1 = "/(.*)\s+(?:in)\s+(.*)/ui"; $expr2 = <<<'REGEX' ~ \s? (?<int> \d{1,5}) \s? (?<time> (?: s (?=(?:ec(?:ond)?s?)?(?:\b|\d)) | m (?=(?:in(?:ute)?s?)?(?:\b|\d)) | h (?=(?:(?:ou)?rs?)?(?:\b|\d)) | d (?=(?:ays?)?(?:\b|\d)) | w (?=(?:eeks?)?(?:\b|\d)) | mon (?=(?:(?:th)?s?)?(?:\b|\d)) ) ) [^\d]*?(?=\b|\d) # do only extract start of string | (?<text> .+) ~uix REGEX; $finalArray = $parsedTimeSpec = []; $leading = $trailing = ""; # If leading text is required, it should separate time and text by "in" # ie. "foo in 9 weeks 5 days" if($requireLeadingString && preg_match($expr1, $input, $parts)){ $leading = $parts['1'] ?? ''; $input = $parts['2']; } $time = preg_replace_callback ($expr2, function($matches) use (&$leading, &$trailing, &$requireTrailingString, &$parsedTimeSpec) { if ($requireTrailingString && isset($matches['text'])) { $trailing = trim($matches['text']); return ''; } switch($matches['time']){ case 's': $t = ' sec '; break; case 'm': $t = ' min '; break; case 'h': $t = ' hour '; break; case 'd': $t = ' day '; break; case 'w': $t = ' week '; break; case 'mon': $t = ' month '; break; } $completeTimeString = $matches['int'].$t; $parsedTimeSpec["$t"] = $matches['int']; return $completeTimeString; }, $input); if ($time != "") { $finalArray['time'] = $parsedTimeSpec; } if ($trailing != "") { $finalArray['trailing'] = $trailing; } if ($leading != "") { $finalArray['leading'] = $leading; } return $finalArray; } $timeSpecWithLeadingString = getTimeSpec($leadingString, true); $timeSpecWithTrailingString = getTimeSpec($trailingString, false, true); $timeSpecWithBoth = getTimeSpec($both, true, true); $timeSpecWithoutText = getTimeSpec($noText, false, false); print_r($timeSpecWithLeadingString); print_r($timeSpecWithTrailingString); print_r($timeSpecWithBoth); print_r($timeSpecWithoutText);
You have javascript disabled. You will not be able to edit any code.
Value for `_results` contains invalid data `array`