The problem is that the lookbehind approach is not so flexible; it crashes when you start communicating with variable length matches. For example, suppose you want to extract the file name in your example, and you did not know the directory name. The capture group technique is still working fine:
preg_match("%^/\w+/([^/]*)%", '/random_length_user/file.php'); Array ( [0] => /random_length_user/file.php [1] => file.php )
... but the lookbehind approach does not, because lookbehind expressions can only match a fixed number of characters. However, there is an even better alternative: \K , the MATCH POINT RESET statement. Wherever you express it, the regex engine pretends that the match really started there. This way you get the same result as with lookbehind, with no fixed length limit:
preg_match('%^/\w+/\K[^/]+$%', '/random_length_user/file.php'); Array ( [0] => file.php )
As far as I know, this function is available only in Perl 5.10+ and in tools (for example, PHP preg_ ), which are supported by the PCRE library. For PCRE help, see the man page and search (F3) for \K
source share