我对正则表达式相当弱,这让我头疼,试图弄明白。我只是想从字符串中提取时间并修改时间的文本。我得到以下形式的字符串:
"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"
我知道在正则表达式中替换的基础知识,但删除我想要的文本前后的多个内容,同时用“小时”替换“小时”等等,超出了我的正则表达式技能水平。
任何帮助都将不胜感激。
感谢。
修改
在搞砸了我之后,我找到了使用多种不同功能的解决方案。我不是很喜欢它,但它确实有效。如果可能的话,我更喜欢单个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 :(得分: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";
}
产生:
2.3 secs
5.2 mins
7.0 hrs
1.9 days
答案 1 :(得分:0)
preg_replace
有一个可选的第4个参数,它是一个限制。
限制是它可以替换的最大匹配数量。
Php preg_replace
它是自动全局的,这意味着它将替换所有匹配项,除非您为该限制设置了正数。
答案 2 :(得分:0)
使用preg_match
和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_callback
和array_search
函数:
...
$testString = preg_replace_callback(["/.*?\b([0-9.]+? )(\w+?)\b.*/"], function($m) use($timeUnitsmap){
return $m[1]. array_search($m[2], $timeUnitsmap);
}, $testString);