Предопределённые константы
Перечисленные ниже константы определены данным модулем и могут быть доступны только в том случае, если PHP был собран с поддержкой этого модуля или же в том случае, если данный модуль был динамически загружен во время выполнения.
Константы | Описание | С версии |
---|---|---|
PREG_PATTERN_ORDER | Меняет порядок элементов в результирующем массиве так, чтобы элемент $matches[0] содержал полные вхождения шаблона, элемент $matches[1] — все вхождения первой взятой в круглые скобки подмаски и т.д. Только preg_match_all() реагирует на данный модификатор. | |
PREG_SET_ORDER | Меняет порядок элементов в результирующем массиве так, чтобы элемент $matches[0] содержал первый набор вхождений (полное вхождение, вхождение первой подмаски, заключённой в круглые скобки. ), аналогично элемент $matches[1] — второй набор вхождений и т.д. Только preg_match_all() реагирует на данный модификатор. | |
PREG_OFFSET_CAPTURE | Смотрите описание флага PREG_SPLIT_OFFSET_CAPTURE . | |
PREG_SPLIT_NO_EMPTY | В случае, если этот флаг указан, функция preg_split() вернёт только непустые подстроки. | |
PREG_SPLIT_DELIM_CAPTURE | В случае, если этот флаг указан, то preg_split() также возвращает выражение, заключённое в круглые скобки в шаблоне разделителя. | |
PREG_SPLIT_OFFSET_CAPTURE | В случае, если этот флаг указан, для каждой найденной подстроки будет указана её позиция в исходной строке. Необходимо помнить, что этот флаг меняет формат возвращаемых данных: каждое вхождение возвращается в виде массива, в нулевом элементе которого содержится найденная подстрока, а в первом — смещение. Этот флаг используется только в функции preg_split() . | |
PREG_UNMATCHED_AS_NULL | Этот флаг указывает preg_match() и preg_match_all() включать несовпадающие подмаски в $matches в виде значений null . Без этого флага несовпадающие подмаски отображаются как пустые строки, как если бы не было найдено совпадений. Установка этого флага позволяет проводить различие между двумя этими случаями. | 7.2.0 |
PREG_NO_ERROR | Возвращается функцией preg_last_error() , если ошибок нет. | 5.2.0 |
PREG_INTERNAL_ERROR | Возвращается функцией preg_last_error() в случае, если произошла внутренняя ошибка PCRE. | 5.2.0 |
PREG_BACKTRACK_LIMIT_ERROR | Возвращается функцией preg_last_error() в случае, когда лимит обратных ссылок был исчерпан. | 5.2.0 |
PREG_RECURSION_LIMIT_ERROR | Возвращается функцией preg_last_error() в случае, если лимит рекурсии был исчерпан. | 5.2.0 |
PREG_BAD_UTF8_ERROR | Возвращается функцией preg_last_error() , если последняя ошибка была вызвана повреждёнными данными UTF-8 (только при запуске в режиме UTF-8). | 5.2.0 |
PREG_BAD_UTF8_OFFSET_ERROR | Возвращается функцией preg_last_error() , если смещение не соответствует началу корректной кодовой точки UTF-8 (только при запуске в режиме UTF-8). | 5.3.0 |
PREG_JIT_STACKLIMIT_ERROR | Возвращается функцией preg_last_error() , если последняя функция PCRE завершилась неудачно из-за лимита стека JIT. | 7.0.0 |
PCRE_VERSION | Версия и дата релиза PCRE (например, » 7.0 18-Dec-2006 «). | 5.2.4 |
User Contributed Notes 2 notes
PREG_PATTERN_ORDER: 1
PREG_SET_ORDER: 2
PREG_OFFSET_CAPTURE: 256
PREG_SPLIT_NO_EMPTY: 1
PREG_SPLIT_DELIM_CAPTURE: 2
PREG_SPLIT_OFFSET_CAPTURE: 4
PREG_NO_ERROR: 0
PREG_INTERNAL_ERROR: 1
PREG_BACKTRACK_LIMIT_ERROR: 2
PREG_RECURSION_LIMIT_ERROR: 3
PREG_BAD_UTF8_ERROR: 4
PREG_BAD_UTF8_OFFSET_ERROR: 5
PCRE_VERSION: %YOUR_VERSION_NUMBER%
The new PREG_JIT_STACKLIMIT_ERROR constant introduced with PHP 7.0.0 has got a value of 6.
I experienced this error code when parsing a 112KB file. preg_match_all failed with this error. Interesting was: The matches array contained some entries, but not all as the command failed (I missed to check the return value).
Unfortunately you can not configure the stack-size of the PCRE JIT. The only way out was — at least for me — to disable the PCRE JIT via php.ini (pcre.jit=0).
preg_match_all
Searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by flags .
After the first match is found, the subsequent searches are continued on from end of the last match.
Parameters
The pattern to search for, as a string.
Array of all matches in multi-dimensional array ordered according to flags .
Can be a combination of the following flags (note that it doesn’t make sense to use PREG_PATTERN_ORDER together with PREG_SET_ORDER ):
PREG_PATTERN_ORDER
Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.
preg_match_all ( «|<[^>]+>(.*)[^>]+>|U» ,
«example:
» ,
$out , PREG_PATTERN_ORDER );
echo $out [ 0 ][ 0 ] . «, » . $out [ 0 ][ 1 ] . «\n» ;
echo $out [ 1 ][ 0 ] . «, » . $out [ 1 ][ 1 ] . «\n» ;
?>?php
The above example will output:
example: ,this is a testexample: , this is a test
So, $out[0] contains array of strings that matched full pattern, and $out[1] contains array of strings enclosed by tags.
If the pattern contains named subpatterns, $matches additionally contains entries for keys with the subpattern name.
If the pattern contains duplicate named subpatterns, only the rightmost subpattern is stored in $matches[NAME] .
The above example will output:
Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on.
preg_match_all ( «|<[^>]+>(.*)[^>]+>|U» ,
«example:
» ,
$out , PREG_SET_ORDER );
echo $out [ 0 ][ 0 ] . «, » . $out [ 0 ][ 1 ] . «\n» ;
echo $out [ 1 ][ 0 ] . «, » . $out [ 1 ][ 1 ] . «\n» ;
?>?php
The above example will output:
example: , example:this is a test, this is a test
If this flag is passed, for every occurring match the appendant string offset (in bytes) will also be returned. Note that this changes the value of matches into an array of arrays where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1 .
preg_match_all ( ‘/(foo)(bar)(baz)/’ , ‘foobarbaz’ , $matches , PREG_OFFSET_CAPTURE );
print_r ( $matches );
?>?php
The above example will output:
Array ( [0] => Array ( [0] => Array ( [0] => foobarbaz [1] => 0 ) ) [1] => Array ( [0] => Array ( [0] => foo [1] => 0 ) ) [2] => Array ( [0] => Array ( [0] => bar [1] => 3 ) ) [3] => Array ( [0] => Array ( [0] => baz [1] => 6 ) ) )
If this flag is passed, unmatched subpatterns are reported as null ; otherwise they are reported as an empty string .
If no order flag is given, PREG_PATTERN_ORDER is assumed.
Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search (in bytes).
Note:
Using offset is not equivalent to passing substr($subject, $offset) to preg_match_all() in place of the subject string, because pattern can contain assertions such as ^, $ or (?<=x). See preg_match() for examples.
Return Values
Returns the number of full pattern matches (which might be zero), or false on failure.
Errors/Exceptions
If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted.
Changelog
Version | Description |
---|---|
7.2.0 | The PREG_UNMATCHED_AS_NULL is now supported for the $flags parameter. |
Examples
Example #1 Getting all phone numbers out of some text.
Example #2 Find matching HTML tags (greedy)
preg_match_all ( «/(<([\w]+)[^>]*>)(.*?)()/» , $html , $matches , PREG_SET_ORDER );
foreach ( $matches as $val ) echo «matched: » . $val [ 0 ] . «\n» ;
echo «part 1: » . $val [ 1 ] . «\n» ;
echo «part 2: » . $val [ 2 ] . «\n» ;
echo «part 3: » . $val [ 3 ] . «\n» ;
echo «part 4: » . $val [ 4 ] . «\n\n» ;
>
?>
The above example will output:
matched: bold text part 1: part 2: b part 3: bold text part 4: matched: click me part 1: part 2: a part 3: click me part 4:
Example #3 Using named subpattern
preg_match_all ( ‘/(?P\w+): (?P\d+)/’ , $str , $matches );
The above example will output:
Array ( [0] => Array ( [0] => a: 1 [1] => b: 2 [2] => c: 3 ) [name] => Array ( [0] => a [1] => b [2] => c ) [1] => Array ( [0] => a [1] => b [2] => c ) [digit] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [2] => Array ( [0] => 1 [1] => 2 [2] => 3 ) )
See Also
- PCRE Patterns
- preg_quote() — Quote regular expression characters
- preg_match() — Perform a regular expression match
- preg_replace() — Perform a regular expression search and replace
- preg_split() — Split string by a regular expression
- preg_last_error() — Returns the error code of the last PCRE regex execution
- PCRE Functions
- preg_filter
- preg_grep
- preg_last_error_msg
- preg_last_error
- preg_match_all
- preg_match
- preg_quote
- preg_replace_callback_array
- preg_replace_callback
- preg_replace
- preg_split