我在正则表达式上相当薄弱,这给我一个头痛,试图弄清楚。我只是试图从字符串中提取时间并修改时间的文本。我得到的字符串有以下几种形式: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
你想为多个字符串一个接一个,或一个包含多个句单一的字符串进行替换? – RomanPerekhrest
字符串将被逐个处理 – Wallboy
可以使用一个preg_replace调用和一个正则表达式。 –