Php pattern match array

preg_match

Ищет в заданном тексте subject совпадения с шаблоном pattern .

Список параметров

В случае, если указан дополнительный параметр matches , он будет заполнен результатами поиска. Элемент $matches[0] будет содержать часть строки, соответствующую вхождению всего шаблона, $matches[1] — часть строки, соответствующую первой подмаске, и так далее.

flags может принимать значение следующего флага: PREG_OFFSET_CAPTURE В случае, если этот флаг указан, для каждой найденной подстроки будет указана ее позиция в исходной строке. Необходимо помнить, что этот флаг меняет формат возвращаемого массива matches в массив, каждый элемент которого содержит массив, содержащий в индексе с номером 0 найденную подстроку, а смещение этой подстроки в параметре subject — в индексе 1.

Обычно поиск осуществляется слева направо, с начала строки. Можно использовать дополнительный параметр offset для указания альтернативной начальной позиции для поиска (в байтах).

Замечание:

Использование параметра offset не эквивалентно замене сопоставляемой строки выражением substr($subject, $offset) при вызове функции preg_match() , поскольку шаблон pattern может содержать такие условия как ^, $ или (?<=x). Сравните:

$subject = «abcdef» ;
$pattern = ‘/^def/’ ;
preg_match ( $pattern , $subject , $matches , PREG_OFFSET_CAPTURE , 3 );
print_r ( $matches );
?>

Результат выполнения данного примера:

В то время как этот пример

$subject = «abcdef» ;
$pattern = ‘/^def/’ ;
preg_match ( $pattern , substr ( $subject , 3 ), $matches , PREG_OFFSET_CAPTURE );
print_r ( $matches );
?>

Array ( [0] => Array ( [0] => def [1] => 0 ) )

Возвращаемые значения

preg_match() возвращает 1, если параметр pattern соответствует переданному параметру subject , 0 если нет, или FALSE в случае ошибки.

Эта функция может возвращать как boolean FALSE , так и не-boolean значение, которое приводится к FALSE . За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Список изменений

Версия Описание
5.3.6 Возвращает FALSE если offset больше, чем длина subject .
5.2.2 Именованные подмаски теперь позволяют синтаксис (?) и (?’name’), также как и (?P). Предыдущие версии позволяли только (?P).

Примеры

Пример #1 Поиск подстроки «php» в тексте

// Символ «i» после закрывающего ограничителя шаблона означает
// регистронезависимый поиск.
if ( preg_match ( «/php/i» , «PHP is the web scripting language of choice.» )) echo «Вхождение найдено.» ;
> else echo «Вхождение не найдено.» ;
>
?>

Пример #2 Поиск слова «web» в тексте

/* Специальная последовательность \b в шаблоне означает границу слова,
* следовательно, только изолированное вхождение слова ‘web’ будет
соответствовать маске, в отличие от «webbing» или «cobweb» */
if ( preg_match ( «/\bweb\b/i» , «PHP is the web scripting language of choice.» )) echo «Вхождение найдено.» ;
> else echo «Вхождение не найдено.» ;
>

if ( preg_match ( «/\bweb\b/i» , «PHP is the website scripting language of choice.» )) echo «Вхождение найдено.» ;
> else echo «Вхождение не найдено.» ;
>
?>

Пример #3 Извлечение доменного имени из URL

// Извлекаем имя хоста из URL
preg_match ( ‘@^(?:http://)?([^/]+)@i’ ,
«http://www.php.net/index.html» , $matches );
$host = $matches [ 1 ];

Читайте также:  Html add color to heading

// извлекаем две последние части имени хоста
preg_match ( ‘/[^.]+\.[^.]+$/’ , $host , $matches );
echo «доменное имя: < $matches [ 0 ]>\n» ;
?>

Результат выполнения данного примера:

Пример #4 Использование именованных подмасок

/* Это также работает в PHP 5.2.2 (PCRE 7.0) и более поздних версиях,
* однако, вышеуказанная форма рекомендуется для обратной совместимости */
// preg_match(‘/(?\w+): (?\d+)/’, $str, $matches);

Результат выполнения данного примера:

Array ( [0] => foobar: 2008 [name] => foobar [1] => foobar [digit] => 2008 [2] => 2008 )

Примечания

Не используйте функцию preg_match() , если необходимо проверить наличие подстроки в заданной строке. Используйте для этого strpos() либо strstr() , поскольку они выполнят эту задачу гораздо быстрее.

Смотрите также

  • «Регулярные выражения PCRE»
  • preg_quote() — Экранирует символы в регулярных выражениях
  • preg_match_all() — Выполняет глобальный поиск шаблона в строке
  • preg_replace() — Выполняет поиск и замену по регулярному выражению
  • preg_split() — Разбивает строку по регулярному выражению
  • preg_last_error() — Возвращает код ошибки выполнения последнего регулярного выражения PCRE

Источник

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:

this is a test

» ,
$out , PREG_PATTERN_ORDER );
echo $out [ 0 ][ 0 ] . «, » . $out [ 0 ][ 1 ] . «\n» ;
echo $out [ 1 ][ 0 ] . «, » . $out [ 1 ][ 1 ] . «\n» ;
?>

The above example will output:

example: , 
this is a test
example: , 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:

this is a test

» ,
$out , PREG_SET_ORDER );
echo $out [ 0 ][ 0 ] . «, » . $out [ 0 ][ 1 ] . «\n» ;
echo $out [ 1 ][ 0 ] . «, » . $out [ 1 ][ 1 ] . «\n» ;
?>

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 .

Читайте также:  Bitrix24 rest api php

preg_match_all ( ‘/(foo)(bar)(baz)/’ , ‘foobarbaz’ , $matches , PREG_OFFSET_CAPTURE );
print_r ( $matches );
?>

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

    Источник

    preg_grep

    Returns the array consisting of the elements of the array array that match the given pattern .

    Parameters

    The pattern to search for, as a string.

    If set to PREG_GREP_INVERT , this function returns the elements of the input array that do not match the given pattern .

    Return Values

    Returns an array indexed using the keys from the array array, or false on failure.

    Errors/Exceptions

    If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted.

    Examples

    Example #1 preg_grep() example

    // return all array elements
    // containing floating point numbers
    $fl_array = preg_grep ( «/^(\d+)?\.\d+$/» , $array );
    ?>

    See Also

    • PCRE Patterns
    • preg_quote() — Quote regular expression characters
    • preg_match_all() — Perform a global regular expression match
    • preg_filter() — Perform a regular expression search and replace
    • preg_last_error() — Returns the error code of the last PCRE regex execution

    User Contributed Notes 4 notes

    A shorter way to run a match on the array’s keys rather than the values:

    function preg_grep_keys ( $pattern , $input , $flags = 0 ) return array_intersect_key ( $input , array_flip ( preg_grep ( $pattern , array_keys ( $input ), $flags )));
    >
    ?>

    Run a match on the array’s keys rather than the values:

    function preg_grep_keys ( $pattern , $input , $flags = 0 )
    $keys = preg_grep ( $pattern , array_keys ( $input ), $flags );
    $vals = array();
    foreach ( $keys as $key )
    $vals [ $key ] = $input [ $key ];
    >
    return $vals ;
    >

    This may be obvious to most experienced developers,but just in case its not,when using preg_grep to check for whitelisted items ,one must be very careful to explicitly define the regex boundaries or it will fail
    $whitelist = [ «home» , «dashboard» , «profile» , «group» ];
    $possibleUserInputs = [ «homd» , «hom» , «ashboard» , «settings» , «group» ];
    foreach( $possibleUserInputs as $input )
    if( preg_grep ( «/ $input /i» , $whitelist )
    echo $input . » whitelisted» ;
    >else echo $input . » flawed» ;
    >

    homd flawed
    hom whitelisted
    ashboard whitelisted
    settings flawed
    group whitelisted

    I think this is because if boundaries are not explicitly defined,preg_grep looks for any instance of the substring in the whole array and returns true if found.This is not what we want,so boundaries must be defined.

    foreach( $possibleUserInputs as $input )
    if( preg_grep ( «/^ $input $/i» , $whitelist )
    echo $input . » whitelisted» ;
    >else echo $input . » flawed» ;
    >

    >
    ?>
    this results in:
    homd flawed
    hom flawed
    ashboard flawed
    settings flawed
    group whitelisted
    in_array() will also give the latter results but will require few tweaks if say,the search is to be case insensitive,which is always the case 70% of the time

    An even shorter way to run a match on the array’s keys rather than the values:

    function preg_grep_keys ( $pattern , $input , $flags = 0 ) return array_flip ( preg_grep ( $pattern , array_flip ( $input ), $flags ) );
    >
    ?>

    • 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

      Источник

Оцените статью