Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make regexp not hungry with quotes?

Tags:

regex

php

unicode

how to make it not hungry - preg_match_all('/"[\p{L}\p{Nd}а-яА-ЯёЁ -_\.\+]+"/ui', $outStr, $matches);

like image 363
Arthur Kushman Avatar asked May 12 '11 12:05

Arthur Kushman


2 Answers

Do you mean non-greedy, as in find the shortest match instead of the longest? The *, +, and ? quantifiers are greedy by default and will match as much as possible. Add a question mark after them to make them non-greedy.

preg_match_all('/"[\p{L}\p{Nd}а-яА-ЯёЁ -_\.\+]+?"/ui', $outStr, $matches);

Greedy match:

"foo" and "bar"
^^^^^^^^^^^^^^^

Non-greedy match:

"foo" and "bar"
^^^^^
like image 81
John Kugelman Avatar answered Sep 21 '22 11:09

John Kugelman


See: http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

U (PCRE_UNGREEDY)

This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by ?. It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?).

like image 39
Yoshi Avatar answered Sep 18 '22 11:09

Yoshi