将时间戳更改为短代码正则表达式

时间:2016-10-27 07:10:30

标签: regex

我正在将时间戳更改为短代码我已经有代码。

$pattern = '/(\d{1,2}:\d{2}(?::\d{2})?)(?!.*?["\'])/';
$replacement = '[spp-timestamp time="${1}"]';
$foundTimestamp = preg_replace ($pattern,$replacement, $content);

哪种方法很完美。

但我不想要选择包含am,pm

的时间戳

例如上午01:00或00:01:00 am和01:00 pm或00:01:00 pm

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以使用

'~(?<!:)\d{1,2}:\d{2}(?::\d{2})?(?!(?::\d{2})?\s*[ap]\.?m\.?)(?!.*?["\'])~i'

替换为[spp-timestamp time="$0"],其中$0是整个匹配反向引用。

请参阅regex demo

如果在前1或2位数之前有:,并且如果时间有PM或AM(带有可选点)之后,则负向前瞻(?!(?::\d{2})?\s*[ap]\.?m\.?)未通过匹配,则初始负向lookbehind会使匹配失败

PHP demo

$re = '/(?<!:)\d{1,2}:\d{2}(?::\d{2})?(?!(?::\d{2})?\s*[ap]\.?m\.?)(?!.*?["\'])/i';
$str = '34:67:56  01:00am or 00:01:00am and 01:00pm or 00:01:00pm';
$result = preg_replace($re, '[spp-timestamp time="$0"]', $str);
echo $result;
// => [spp-timestamp time="34:67:56"]  01:00am or 00:01:00am and 01:00pm or 00:01:00pm