php - Is it better to use look-behind or capture groups? -


I'm not sure any of these is 'better', second, and why it will be, they have an original string That looks like this:

  $ string = '/random_length_user/file.php';  

Now, there are two ways to match it, first, my new friend, look-back, and without the other:

  Preg_match ("% (? & Lt; = ^ /) ([^ /] *)% ", $ string, capture $); Preg_match ("% ^ / ([^ /] *)%", $ string, $ capture);  

They come back in sequence:

  array ([0] = & amp;; random_length_user) array ([0] => Random_length_user [1] = & gt; random_length_user)  

Basically I'm getting the result that I want to use [0] back-behind in $ capture, and $ capture Without this [1] the question now is ... do any of these methods like?

The problem is that the look-up method is not flexible; When you start dealing with variable-length matches, it falls down. For example, suppose you wanted to remove the filename in your example, and you did not know the name of the directory. Capturing-group technology still works fine:

  preg_match ("% ^ / \ w + / ([^ /] *)%", '/ random_length_user / file.php') ; Array ([0] = & gt; /random_length_user/file.php [1] = & gt; file.php)  

... but not the tracking approach, because see Expressions of expressions only match the number of fixed characters. However, here's an even better option: \ K , match point reset operator wherever you put it, the regex engine shows that the match really starts. So you can get the same result, as you will see without the fixed length limit:

  preg_match ('% ^ / \ w + / \ K [^ /] + $ % ',' /random_length_user/file.php '); Array ([0] = & gt; file.php)  

As far as I know, this feature is only available in Perl 5.10+ and in Tools (such as PHP's Preg _ function) for PCI reference, see \ K for search and search (F3) which are operated by PCRE libraries.


Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -