我尝试获取字符串中使用的分钟或小时。
示例 1:
$string = "I walked for 2hours";
// preg_match here
$output = "2 hours";
示例 2:
$string = "30min to mars";
// preg_match here
$output = "30 minutes";
已经阅读了下面的问题。但不能解决我的问题: preg_match 查找以某个字符结尾的单词
我尝试获取字符串中使用的分钟或小时。
示例 1:
$string = "I walked for 2hours";
// preg_match here
$output = "2 hours";
示例 2:
$string = "30min to mars";
// preg_match here
$output = "30 minutes";
已经阅读了下面的问题。但不能解决我的问题: preg_match 查找以某个字符结尾的单词
$string = "I walked for 30hours and 22min";
$pattern_hours = '/^.*?([0-9]+)hours.*$/';
echo preg_replace($pattern_hours, '${1} hours', $string),"\n";
$pattern_min = '/^.*?([0-9]+)min.*$/';
echo preg_replace($pattern_min, '${1} minutes', $string),"\n";
请随时提出问题。代码在 PHP 5.3 输出中进行了测试:
30 hours
22 minutes
只需替换/([0-9]+)\s*(hours?|minutes?|seconds?|mins?|secs?)/i
为$1 $2
:
<?php
$string = "I walked for 2hours and 45 mins to get there";
$string = preg_replace("/([0-9]+)\s*(hours?|minutes?|seconds?|mins?|secs?)/i", "$1 $2", $string);
var_dump($string);
//string(45) "I walked for 2 hours and 45 mins to get there"
?>
这将适用于
时
时
分
分 分
分
分
秒
秒
秒
秒
任何大小写(但不会替换mins
为minutes
等)
或者,如果您真的想用不同的标记(分钟到分钟等)替换,请使用preg_replace_callback
:
<?php
function replaceTimes($matches) {
$times = array(
"hour" => array("hour"),
"minute" => array("min", "minute"),
"second" => array("sec", "second")
);
$replacement = $matches[1] . " " . $matches[2];
foreach ($times as $time => $tokens) {
if (in_array($matches[2], $tokens)) {
$replacement = $matches[1] . " " . $time . ($matches[1] != "1" ? "s" : "");
break;
}
}
return $replacement;
}
$string = "I walked for 2hours and 45 mins to get there as well as 1 secs to get up there";
$string = preg_replace_callback("/([0-9]+)\s*(hour|minute|second|min|sec)s?/i", "replaceTimes", $string);
var_dump($string);
?>
它会自动修复标记末尾的“s”以及其他所有内容:
string(84) "我走了 2 小时 45 分钟才到那里,还有 1 秒才爬上去"
<?php
$string = "I walked for 2hours and 30min";
$pattern_hours = '/([0-9]{0,2})hours/';
$pattern_min = '/([0-9]{0,2})min/';
if(preg_match($pattern_hours, $string, $matches, PREG_OFFSET_CAPTURE, 3)) {
// echo the match hours
} elseif(preg_match($pattern_min, $string, $matches, PREG_OFFSET_CAPTURE, 3)) {
// echo the match minutes
}
?>