Php preg match это

PHP Regular Expressions

Summary: in this tutorial, you’ll learn about PHP regular expressions and functions that work with regular expression including preg_match() , preg_match_all() , and preg_replace() .

Introduction to the PHP regular expressions

PHP string functions allow you to test if a string contains a substring ( str_contains() ) or to replace all occurrences of a substring with another string ( str_replace() ).

However, these functions deal with fixed patterns. They won’t work with flexible patterns. For example, if you want to search any numbers in a string, the str_contains() won’t work.

To search or replace a string using a pattern, you use regular expressions.

A regular expression is a string that describes a pattern such as phone numbers, credit card numbers, and email addresses.

Create regular expressions

To create a regular expression, you place a pattern in forward-slashes like this:

'/pattern/';Code language: PHP (php)
 $pattern = '/\d+/';Code language: PHP (php)

The $pattern is a string. Also, it is a regular expression that matches a number with one or more digits. For example, it matches the numbers 1, 20, 300, etc.

Note that you’ll learn how to form flexible regular expressions in the following tutorial.

The forward-slashes are delimiters. The delimiters can be one of the following characters ~ , ! , @ , # , $ or braces including <> , () , [] , <> . The braces help improve regular expressions’ readability in some cases.

Note that you cannot use the alphanumeric, multi-byte, and backslashes ( \ ) as delimiters.

The following regular expression uses the curly braces as delimiters:

 $pattern = '';Code language: PHP (php)

Search strings using regular expressions

To search a string for a match to a pattern, you use the preg_match() and preg_match_all() functions.

PHP preg_match() function

To search based on a regular expression, you use the preg_match() function. For example:

 $pattern = ''; $message = 'PHP 8 was released on November 26, 2020'; if (preg_match($pattern, $message)) < echo "match"; > else < echo "not match"; >Code language: PHP (php)
matchCode language: PHP (php)

The preg_match() searches the $message for a match to the $pattern .

The preg_match() function returns 1 if there is a match in the $message , 0 if it doesn’t, or false on failure.

To get the text that matches the pattern, you add the third parameter to the preg_match() function like the following example:

 $pattern = ''; $message = 'PHP 8 was released on November 26, 2020'; if (preg_match($pattern, $message, $matches)) Code language: PHP (php)
Array ( [0] => 8 )Code language: PHP (php)

The $matches parameter contains all the matches. The $matches[0] stores the text that matches the pattern. In this example, it is the number 8.

The $matches[1] , $matches[2] , … store the texts that match the first, second,… capturing group —more on this in the capturing group tutorial.

The preg_match() only returns the first match and stops searching as soon as it finds the first one. To find all matches, you use the preg_match_all() function.

PHP preg_match_all() function

The preg_match_all() function searches for all matches to a regular expression. For example:

 $pattern = ''; $message = 'PHP 8 was released on November 26, 2020'; if (preg_match_all($pattern, $message, $matches)) Code language: PHP (php)
Array ( [0] => Array ( [0] => 8 [1] => 26 [2] => 2020 ) )Code language: PHP (php)

In this example, the preg_match_all() puts all matches in a multidimensional array with the first element contains the texts ( 8 , 26 , and 2020 ) that match the pattern.

The preg_match_all() function returns the number of matches, which can be zero or a positive number.

Replace strings using regular expressions

To replace strings that match a regular expression, you use the preg_replace() function. For example:

 $pattern = '/\d+/'; $message = 'PHP 8 was released on 11/26/2020'; echo preg_replace($pattern, '%d', $message); Code language: PHP (php)
PHP %d was released on %d/%d/%d

In this example, the preg_replace() function replaces all numbers in the $message with the string %d .

Summary

  • PHP regular expressions are strings with pattern enclosing in delimiters for example «/pattern/» .
  • The preg_match() function searches for a match to a pattern in a string.
  • The preg_match_all() function searches for all matches to a pattern in a string.
  • The preg_replace() function searches a string for matches to a pattern and replaces them with a new string or pattern.

Источник

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 ];

// извлекаем две последние части имени хоста
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

Источник

Читайте также:  Php file csv write
Оцените статью