我在正则表达式方面相当弱,这让我头疼要尝试找出答案。我只是想从字符串中提取时间并修改时间的文本。我得到以下形式的字符串:
"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
如果您确实想在一行中进行搜索/替换,则可以执行以下操作:
$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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句