2016-04-21 122 views
0

我在正則表達式上相當薄弱,這給我一個頭痛,試圖弄清楚。我只是試圖從字符串中提取時間並修改時間的文本。我得到的字符串有以下幾種形式:PHP preg_replace多個替換

"Some text I don't care about | 2.3 seconds ago" 
"Some text I don't care about | 5.2 minutes ago" 
"Some text I don't care about | 7.0 hours ago" 
"Some text I don't care about | 1.9 days ago" 

我想換成上述字符串它們分別是在形式:

"2.3 secs" 
"5.2 mins" 
"7.0 hrs" 
"1.9 days" 

我知道正則表達式替換的基礎知識,但刪除多個我想要的文本前後的東西,而用「hrs」替換「小時」等,超出了我的正則表達式技能水平。

任何幫助,將不勝感激。

感謝。

編輯:

搞亂我使用多個不同的功能來解決好了後。我不完全喜歡它,但它有效。如果可能,我寧願單個preg_replace解決方案。這是我目前解決方案:

$testString = "This is text I don't care about | 7.3 seconds ago"; 
$testString = array_shift(array_reverse(explode('|', $testString))); 
$pattern = array('/seconds/', '/minutes/', '/hours/', '/ago/'); 
$replace = array('secs', 'mins', 'hrs', ''); 
$testString = trim(preg_replace($pattern, $replace, $testString)); 

輸出爲:7.3 secs

+0

你想爲多個字符串一個接一個,或一個包含多個句單一的字符串進行替換? – RomanPerekhrest

+0

字符串將被逐個處理 – Wallboy

+0

可以使用一個preg_replace調用和一個正則表達式。 –

回答

1

如果你真的想在同一行的查找/替換,你可以做這樣的事情:

$time_map = array(
    'seconds' => 'secs', 
    'minutes' => 'mins', 
    'hours' => 'hrs', 
    'days' => 'days', 
); 

$data = array(
    "Some text I don't care about | 2.3 seconds ago", 
    "Some text I don't care about | 5.2 minutes ago", 
    "Some text I don't care about | 7.0 hours ago", 
    "Some text I don't care about | 1.9 days ago", 
); 

foreach ($data as $line) { 
    $time_data = preg_replace_callback("/(.*|\s*)([0-9]+\.[0-9]+) (\w+) ago/", function ($matches) use ($time_map) {return $matches[2] . " " . $time_map[$matches[3]];}, $line); 
    print "$time_data\n"; 
} 

主要生產:使用preg_match

2.3 secs 
5.2 mins 
7.0 hrs 
1.9 days 
+0

謝謝,那會很好。 – Wallboy

0

preg_replace有一個可選的第四個參數是一個限制。 該限制是它可以替代的最大匹配數量。 Php preg_replace它是自動全局的,這意味着它會替換所有匹配,除非您將正數設置爲限制。

http://php.net/manual/en/function.preg-replace.php

0

簡單的解決方案str_replace功能:

$testString = "This is text I don't care about | 7.3 seconds ago"; 
$timeUnitsmap = ["secs" => "seconds", "mins" => "minutes", "hrs" => "hours"]; 

preg_match("/\b[0-9.]+? \w+?\b/i", $testString, $matches); 
$testString = str_replace(array_values($timeUnitsmap), array_keys($timeUnitsmap), $matches[0]); 

print_r($testString); // "7.3 secs" 

或者使用preg_replace_callbackarray_search功能:

... 
$testString = preg_replace_callback(["/.*?\b([0-9.]+?)(\w+?)\b.*/"], function($m) use($timeUnitsmap){ 
    return $m[1]. array_search($m[2], $timeUnitsmap); 
}, $testString);