Helpful Information
 
 
Category: Regex Programming
Help with lookbehind assertion and fixed width

ok how do i make a variable length lookbehind in php?


(?<![\s]*to[\s]*)

http://www.perl.com/doc/manual/html/pod/perlre.html

[edit] You can't do variable-length negative lookbehinds. At least not in PHP.

no that wont work.

you get this



[09-Sep-2008 19:35:45] PHP Warning: preg_match() [<a href='https://forums.devshed.com/archive/index.php/function.preg-match'>function.preg-match</a>]: Compilation failed: lookbehind assertion is not fixed length at offset 104



in the link i provided



(?=pattern)

A zero-width positive lookahead assertion. For example, /\w+(?=\t)/ matches a word followed by a tab, without including the tab in $&.

(?!pattern)

A zero-width negative lookahead assertion. For example /foo(?!bar)/ matches any occurrence of ``foo'' that isn't followed by ``bar''. Note however that lookahead and lookbehind are NOT the same thing. You cannot use this for lookbehind.

If you are looking for a ``bar'' that isn't preceded by a ``foo'', /(?!foo)bar/ will not do what you want. That's because the (?!foo) is just saying that the next thing cannot be ``foo''--and it's not, it's a ``bar'', so ``foobar'' will match. You would have to do something like /(?!foo)...bar/ for that. We say ``like'' because there's the case of your ``bar'' not having three characters before it. You could cover that this way: /(?:(?!foo)...|^.{0,2})bar/. Sometimes it's still easier just to say:

if (/bar/ && $` !~ /foo$/)

For lookbehind see below.

(?<=pattern)

A zero-width positive lookbehind assertion. For example, /(?<=\t)\w+/ matches a word following a tab, without including the tab in $&. Works only for fixed-width lookbehind.

(?<!pattern)

A zero-width negative lookbehind assertion. For example /(?<!bar)foo/ matches any occurrence of ``foo'' that isn't following ``bar''. Works only for fixed-width lookbehind.


i kind of get it, but its still sinking in. looking for a clear answer as to why i cant make it a variable length i.e. your solution

i dont understand


cover that this way: /(?:(?!foo)...|^.{0,2})bar/. Sometimes it's still easier just to say:

if (/bar/ && $` !~ /foo$/)

My first reply was because I had flipped the ! and > in my head. I saw (?!< (non-capturing, has a <) instead of the (?<! (negative lookbehind) you posted. Thus the edit.

It's just a limitation of the engine, which PHP copied to some extent. There's just no support for that kind of thing.

yea i understand the logic behind the no support.

basically its fine for a lookahead because it goes until the end. but a lookbehind has the opportunity for an endless recursion loop. meaning i could box it inbetween two "to"










privacy (GDPR)