Mike Mike - 14 days ago 5
PHP Question

join few regex patterns (not some str, any words, date)

I got three working regex patterns:

^(sezon\s[0-9]+) => finds if string starts with sezon $$ where $is digit
([a-zA-z]*|\b)*.* => that should match any words
\d{1,2}[.]\d{1,2}[.]\d{2,4} => that matches date


Now I want to negate first and third pattern and join them into second.

Sezon 2 some text here 03.02.1203 => should be excluded
Sezon more text => included
Sezon 2 mote set amet => excluded
some date here 20.20.2222 =>excluded
only text here also => included
2 - => excluded


What I'm trying to achieve is to deny strings with:


  • date at the end,

  • Sezon $ at the beginning

  • 1 - at the beginning



Rest (Sezon some text) (only text) should be accepted

Now I can make 3 preg_matches and then combine theirs outputs in 'if' but I was wondering if it can be done in one pattern. Or maybe different idea entirely?

Real string which will be used:
sezon 1

1 -
Pilot (pilot)
26.10.2015

2 -
Stronger Together
2.11.2015
3 -
Fight or Flight
9.11.2015


Lines are broken by explode function.
For each line string I want to check if its Season, number, title or date and then do different stuff in each case.

Answer

Use a negative lookahead:

'~^(?!\h*\d+\h*-‌|sezon\h+[0-9]+|.*\d{1,2}[.]\d{1,2}[.]\d{2,4}$).+~im'

See the regex demo

Details:

  • ^ - start of string
  • (?!\h*\d+\h*-‌|sezon\h+[0-9]+|.*\d{1,2}[.]\d{1,2}[.]\d{2,4}$) - a negative lookahead that will fail the match if a string starts with 0+ horizontal whitespaces, 1+ digits, 0+ whitespaces and - (see \h*\d+\h*-‌) or starts with sezon, 1+ whitespaces and 1+ digits, or (|) ends with the \d{1,2}[.]\d{1,2}[.]\d{2,4} pattern (as there must be the end of string after it - $)
  • .+ - 1 or more chars other than line break chars.