只需更換/([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"
?>
DEMO
這將爲
小時
小時
0工作個分鐘
分鐘
敏思
民
秒
二
秒]
秒
任何資本的
(但不會取代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」標記的結束,以及其他一切:
串(84), 「我走了2小時45分鐘,以得到有以及1秒到起牀那裏」
DEMO
我認爲這是「* 30秒到火星*」。 ;) – insertusernamehere
大聲笑,你是對的! –
它是否總是格式爲'xhours'和'xmin'? –