Mohammad Umer February 2016

Conditional RgEx with PHP preg_match_all

Just have to select Conditional Regex.

Here is what i have problem....

I just want to select time string 02:00 but not with quotation marks like "02:00" or '02:00'

I am using to select 02:00 or 2:00 Regex is

$pattern = '/(\d{2}:\d{2})|(\d{1}:\d{2})/';
preg_match_all($pattern,$content, $matches); 

But is selecting this also "02:00" or '02:00' I am not sure which regex will use to skip that time string.

I got this http://www.regular-expressions.info/conditional.html But not sure how make regex :(

Please help me out.

UPDATE

Thanks for Lucas Trzesniewski and his Great Help.

I just resolved my issue with this php code.

 $pattern = '/(?!["\'])\b\d{1,2}:\d{2}\b(?!["\'])/';
  preg_match_all($pattern,$content, $matches); 

Answers


Lucas Trzesniewski February 2016

Conditionals won't help you much in this case.

The simplest way is to use lookarounds:

(?<!["'])\b\d{1,2}:\d{2}\b(?!["'])

Demo

  • (?<!["']) (negative lookbehind) will make sure the preceding character is not single or double quote
  • (?!["']) (negative lookahead) will do the same for the following character

Post Status

Asked in February 2016
Viewed 1,724 times
Voted 4
Answered 1 times

Search




Leave an answer