preg_match分钟和小时

时间:2013-09-25 13:45:03

标签: php 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 to find a word that ends in a certain character

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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"
?>

DEMO

这适用于

  

小时
  小时
  分钟
  分钟
  分钟
  闵
  秒
  第二
  秒
  第二节

任何大小写( 但不会将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秒钟到达那里”

DEMO

答案 2 :(得分: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
}

?>