2013-09-25 139 views
0

我嘗試獲取字符串中使用的分鐘或小時數。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

+6

我認爲這是「* 30秒到火星*」。 ;) – insertusernamehere

+0

大聲笑,你是對的! –

+0

它是否總是格式爲'xhours'和'xmin'? –

回答

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 
+0

我只想指出,在'$ string'中有2個'Xhours'只會輸出第一個。 – Christoph

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 
} 

?> 
+0

應該是'/ [0-9] {0,2}小時/''不'^謝謝 –

+0

@LaurentWartel指正!我會改變它:) –

+1

此外,我想他想提取小時數(或分鐘):在這種情況下,他應該使用捕獲括號'([0-9] {0,2})小時。 –

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

這將爲

小時
小時
0工作個分鐘
分鐘
敏思



秒]

任何資本的

但不會取代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」標記的結束,以及其他一切:

串(84), 「我走了2小時45分鐘,以得到有以及1秒到起牀那裏」

DEMO