Preg match with array php

preg_match

Searches subject for a match to the regular expression given in pattern .

Parameters

The pattern to search for, as a string.

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

flags can be a combination of the following flags:

PREG_OFFSET_CAPTURE

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 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('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE); print_r($matches); ?>

The above example will output:

Array ( [0] => Array ( [0] => foobarbaz [1] => 0 ) [1] => Array ( [0] => foo [1] => 0 ) [2] => Array ( [0] => bar [1] => 3 ) [3] => Array ( [0] => baz [1] => 6 ) )

If this flag is passed, unmatched subpatterns are reported as null ; otherwise they are reported as an empty string.

 preg_match('/(a)(b)*(c)/', 'ac', $matches); var_dump($matches); preg_match('/(a)(b)*(c)/', 'ac', $matches, PREG_UNMATCHED_AS_NULL); var_dump($matches); ?>

The above example will output:

array(4) < [0]=> string(2) "ac" [1]=> string(1) "a" [2]=> string(0) "" [3]=> string(1) "c" > array(4) < [0]=> string(2) "ac" [1]=> string(1) "a" [2]=> NULL [3]=> string(1) "c" >

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() in place of the subject string, because pattern can contain assertions such as ^, $ or (?<=x). Compare:

 $subject = "abcdef"; $pattern = '/^def/'; preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3); print_r($matches); ?>

The above example will output:

 $subject = "abcdef"; $pattern = '/^def/'; preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE); print_r($matches); ?>
Array ( [0] => Array ( [0] => def [1] => 0 ) )

Alternatively, to avoid using substr(), use the \G assertion rather than the ^ anchor, or the A modifier instead, both of which work with the offset parameter.

Return Values

preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure.

This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

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 Find the string of text «php»

 // The "i" after the pattern delimiter indicates a case-insensitive search if (preg_match("/php/i", "PHP is the web scripting language of choice.")) < echo "A match was found."; > else < echo "A match was not found."; > ?>

Example #2 Find the word «web»

 /* The \b in the pattern indicates a word boundary, so only the distinct * word "web" is matched, and not a word partial like "webbing" or "cobweb" */ if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) < echo "A match was found."; > else < echo "A match was not found."; > if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) < echo "A match was found."; > else < echo "A match was not found."; > ?>

Example #3 Getting the domain name out of a URL

 // get host name from URL preg_match('@^(?:http://)?([^/]+)@i', "http://www.php.net/index.html", $matches); $host = $matches[1]; // get last two segments of host name preg_match('/[^.]+\.[^.]+$/', $host, $matches); echo "domain name is: \n"; ?>

The above example will output:

Example #4 Using named subpattern

 $str = 'foobar: 2008'; preg_match('/(?P\w+): (?P\d+)/', $str, $matches); /* Alternative */ // preg_match('/(?\w+): (?\d+)/', $str, $matches); print_r($matches); ?>

The above example will output:

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

Notes

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() instead as it will be faster.

See Also

  • PCRE Patterns
  • preg_quote() — Quote regular expression characters
  • preg_match_all() — Perform a global 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
  • preg_last_error_msg() — Returns the error message of the last PCRE regex execution
PHP 8.2

(PHP 5 5.2.0, 7, 8) preg_last_error Returns the code of PCRE regex execution Returns the error code of last PCRE regex execution.

(PHP 8) preg_last_error_msg Returns the message of PCRE regex execution Returns the error message of last PCRE regex execution.

(PHP 4, 5, 7, 8) preg_match_all Perform global regular expression Searches subject for all matches to the regular expression given in pattern and puts

(PHP 4, 5, 7, 8) preg_quote regular expression characters preg_quote() takes str and puts backslash in front of every character that is part the regular

Источник

Регулярные выражения в PHP часть 3 (preg_match)

В предыдущей части статьи «Регулярные выражения в PHP (preg_replace) часть 2» мы говорили исключительно о функции preg_replace, которая заменяет часть строки. Но есть ещё функция preg_match, которая выполняет поиск в строке по регулярному выражению. Эта функция возвращает 1, если хотя бы одно совпадение найдено и 0, если не было найдено ни одного. Приведём пример использования:

Функция preg_match применяется нечасто, потому что всего лишь говорит есть или нет подстрока. Но есть ещё функция preg_match_all, которая имеет три параметра и находит все совпадения, записывая их в третий параметр. Звучит сложно, но посмотрим на практике, что это значит:

В результате выполнения такого кода переменная $b станет равна 2, а в переменной $a будет массив с найденными совпадениями. Результат будет такой:

Array ( [0] => Array ( [0] => Тише [1] => мыши ) )

Карманы

У функции preg_match_all есть возможность выгружать не только найденные совпадения, но и найденные вариации, которые называются карманами. Эти карманы появляются, если использовать скобки ( ) Приведём пример:

Array ( [0] => Array ( [0] => Сыр [1] => сыыр [2] => сыыыр ) [1] => Array ( [0] => ы [1] => ыы [2] => ыыы ) )

В первом массиве будут содержаться найденные совпадения, а во втором содержимое первого кармана. Карманов может быть несколько, в зависимости от количества скобок ( ), которые использовались в регулярном выражении.

Скобки автоматически создают карманы. Если же нужно отказаться от создания кармана, то нужно добавить в начало скобок символы «?:«. Тогда в примере выше регулярное выражение примет такой вид «‘#\bс(?:ы+)р\b#iu‘».

Карманы и preg_replace

Функция preg_replace тоже умеет использовать карманы. Их можно подставлять во второй параметр функции, используя порядковый номер и знак $. Таким образом можно заменять части строки так, что содержащиеся в кармане части будут подставляться на замену.

В первый карман попадёт слово «Сыр», во второй «мышь», а в третий «кот». По правилу ‘$3, $1, $2’ результат будет иметь содержимое из 3 кармана, затем запятую и пробел, потом содержимое 1 кармана с запятой и пробелом, и в конце содержимое 2 кармана. Результат будет такой:

Напомним, что регулярными выражениями необходимо использовать только в том случае, если нет никакого другого способа решения.

Ошибки в регулярных выражениях — это очень частое явление. Поэтому прибегайте к этому инструменту только в самых-самых безвыходных ситуациях, когда всё остальное уже опробовано.

Можно обращаться к содержимому кармана непосредственно в регулярном выражении. То есть в карман заносятся данные и тут же достаются. Для этого необходимо поставить слеш \ и затем номер кармана непосредственно в регулярном выражении:

В приведённом примере выражение «#([а-я]+)\1#» сначала заносит в карман любую букву, а котом достаёт её же и ставит после найденной. Эффект получается такой, как будто мы находим повторяющуюся два раза букву и делаем её замену:

Позитивный и негативный просмотр

Функцией preg_replace найденное выражение заменяется полностью на второй параметр. Но что делать, если нам не надо заменять всё найденное, а только часть? Для этого есть позитивный и негативный просмотр.

Представьте, что нужно заменить слово, не заменяя первую букву. Приведём пример реализации:

Тише, мыши, котята на крыше

Хоть буква «к» и стоит в регулярном выражении, но она стоит в специальных скобках (?<=к), которые проверяют наличие буквы, но не подставляют её на замену. Такие скобки называются позитивным просмотром. Можно сделать позитивный просмотр и в конце строки:

Позитивный просмотр (?=е) проверяет, есть ли в конце строки буква «е». Происходит замена и получается такая строка:

Теперь рассмотрим оба примера (просмотр в начале и в конце строки), но в негативном смысле. Негативный просмотр — это противоположность к позитивному и создаётся с помощью скобок (? для поиска символа вначале и (?! ) в конце. То есть он проверяет нет ли такого символа:

Тише, мыши, кот на крышке Мышка, сырок

Источник

Читайте также:  Java editor for linux
Оцените статью