V. Terte
V. Terte

Reputation: 7

Regex PHP: to look ahead twice

Why this:

/^lol(?=abc)(?=dfg)$/

can't match this

lolabcdfg

Thank you for your answer! It was very kind of you!

Upvotes: 1

Views: 595

Answers (2)

R. Chappell
R. Chappell

Reputation: 1282

Because lookaheads only assert, they do not consume characters... so basically you're saying,

match lol:

lol

then look head for abc:

lol(abc) // matches

now look ahead for dfg

lol(dfg) // does not match

This is why it's not working. You need to consume the characters, if you want to check for both abc and abcdfg. If you only want to look ahead you can do:

/^lol(?=abc|dfg|abcdfg)/

This will match the strings

  • lolabc
  • loldfg
  • lolabcdfg

However it's not very useful. The following would be more appropriate

/^lol(abc)?(dfg)?/

Which would match lol, optionally abc then optionally dfg.

Upvotes: 4

nicowernli
nicowernli

Reputation: 3348

This regex will do

/^lol(abc)?(dfg)?$/

I always use https://regex101.com/ to test my regex online

Upvotes: 1

Related Questions