0

我尝试获取字符串中使用的分钟或小时。

示例 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 查找以某个字符结尾的单词

4

3 回答 3

2
$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
于 2013-09-25T14:14:21.180 回答
1

只需替换/([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"
?>

演示

这将适用于




分 分





任何大小写(但不会替换minsminutes


或者,如果您真的想用不同的标记(分钟到分钟等)替换,请使用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 秒才爬上去"

演示

于 2013-09-25T14:19:45.423 回答
0
<?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
}

?>
于 2013-09-25T13:49:42.630 回答