V. Terte V. Terte - 15 days ago 8
PHP Question

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!

Answer

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.