-2

My pattern works in JavaScript.

(?<=(?:username|Email|URL)(?:\s|:))[^\n]+

However, when I try to use it in PHP, I get this error:

A lookbehind assertion has to be fixed width

How I can fix it?

Demo: https://regex101.com/r/x2W3S5/1

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Kadi
  • 37
  • 6

2 Answers2

1

Use a full string match restart (\K) instead of the invalid variable-length lookbehind.

Regex 101 Demo

/^(?:username|Email|Url):? *\K\V+/mi

Make the colon and space optional by trailing them with ? or *.

Use \V+ to match the remaining non-vertical (such as \r and \n) characters excluding in the line.

See the broader canonical: Variable-length lookbehind-assertion alternatives for regular expressions


To protect your script from falsely matching values instead of matching labels, notice the use ^ with the m modifier. This will ensure that you are matching labels that occur at the start of a line.

Without a start of line anchor, Somethingelse: url whoops will match whoops.

To make multiple matches in PHP, the g pattern modifier is not used. Instead, apply the pattern in preg_match_all()

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • `[^\v]` is a strange choice, why to not use the dot? Or if you want something that do not depend of an eventual s modifier, you can use `\N`. – Casimir et Hippolyte Apr 29 '22 at 08:12
  • Yes, you are right. I got sucked by the OP's `[^\n]`. Fixed. – mickmackusa Apr 29 '22 at 11:00
  • Note that it's uncommon, but it can be useful to use `\V` in place of the dot when the default newline sequence is set to `\n` for the regex engine and is `\r\n` in the string (in this case the dot will match `\r` and you have to trim the result after). It's shorter than `[^\r\n]` and it's shorter than setting allowed newline sequences in the pattern https://3v4l.org/Qk180 – Casimir et Hippolyte Apr 29 '22 at 11:50
  • You've really got me chasing my tail today. – mickmackusa Apr 29 '22 at 12:15
0

Sadly, js does't have regexp lookbehide. This may help you solve this: javascript regex lookbehide alternative

M.Smith
  • 1
  • 1
  • 1
    I realize that you don't yet have the privilege to comment under the question, but both parts of your answer (1. why it doesn't work and 2. where to look for insights regarding the problem) are better offered as comments instead of an answer. No part of your answer provides resolution for this PHP problem. – mickmackusa Apr 29 '22 at 02:41