preg_match查找以某个字符结尾的单词


preg_match to find a word that ends in a certain character

我正在尝试制作一个小程序,在计时器内搜索(格式为00d 00h 00m 00s),并将日期返回到一个变量,将小时返回到另一个变量等。

这是我的一些代码:

$time1 = "Left: 11d 21h 50m 06s <'/div>"
preg_match_all("/ .*d/i", $time1, $timematch); // Day
$time1day = $timematch[1]; // Saves to variable
preg_match_all("/ .*h/i", $time1, $timematch); // Hour
$time1hour = $timematch[1]; // Saves to variable
preg_match_all("/ .*m/i", $time1, $timematch); // Minute
$time1minute = $timematch[1]; // Saves to variable
preg_match_all("/ .*s/i", $time1, $timematch); // Second
$time1second = $timematch[1]; // Saves to variable

我的正则表达式不正确,但我不确定它应该是什么。有什么想法吗?

顺便说一下,我正在使用PHP4。

此正则表达式将完成以下操作:

('d+)d ('d+)h ('d+)m ('d+)s

每个值(天、小时、分钟、秒)都将在一个组中捕获。

关于您的正则表达式:我不知道您所说的"不正确"是什么意思,但我想它可能失败了,因为您的正则函数是贪婪的,而不是懒惰的(更多信息)。尝试使用惰性运算符,或者使用更具体的匹配(例如,'d而不是.)。

编辑:

我需要它们是独立的变量

匹配后,它们将被放在结果数组中的不同位置。只需将它们分配给变量即可。看看这里的例子。

如果您无法理解生成的数组结构,那么在调用preg_match_all时可能需要使用PREG_SET_ORDER标志(此处提供更多信息)。

如果格式总是按照您显示的顺序,我不会正则化它

$time1= "Left: 11d 21h 50m 06s <'/div>";     
$timeStringArray = explode(" ",$timeString);
$time1day = str_replace("d","",$timeStringArray[1]);
$time1hour = str_replace("h","",$timeStringArray[2]);
$time1minute = str_replace("m","",$timeStringArray[3]);
$time1second = str_replace("s","",$timeStringArray[4]);

如果模式总是这样,两位数字加上时间字母,你可以这样做:

$time1 = "Left: 11d 21h 50m 06s <'/div>";
preg_match_all("/('d{2})[dhms]/", $time1, $match);
print_r($match);

UPDATE:此函数可以使用1或2位数字,并匹配所有参数。

$time1 = "Left: 11d 21h 50m 06s <'/div>";
$time2 = "Left: 21h 50m 5s";
$time3 = "Left: 9m 15s";
function parseTime($str) {
    $default = array('seconds', 'minutes', 'hours', 'days');
    preg_match_all("/('d{1,2})[dhms]/", $str, $time);
    if (!isset($time[1]) || !is_array($time[1])) {
        return null;
    }
    $default = array_slice($default, 0, count($time[1]));
    return array_combine($default, array_reverse($time[1]));
}
print_r(parseTime($time1));
print_r(parseTime($time2));
print_r(parseTime($time3));