Примеры регулярных выражений для PHP
В таблице показаны результаты работы следующей функции:
preg_match($pattern, $text, $matches)
Описание | $pattern - регулярное выражение | $text | $matches |
---|---|---|---|
Целое положительное число | '/\d+/' | text 1234 text | $matches[0] == '1234' |
Пароль (латинские буквы, цифры, подчерк) | '/^\w+$/i' | pass_1 | $matches[0] == 'pass_1' |
It's not a password | $matches[0] == '' | ||
пароль | $matches[0] == '' | ||
Текст в кавычках (в т.ч. русский) | '/"(\pL+)"/ui' | текст в "двойных" кавычках |
$matches[0] == '"двойных"' $matches[1] == 'двойных' |
This is a "quoted" text |
$matches[0] == '"quoted"' $matches[1] == 'quoted' |
||
Дата (упрощенный вариант) | '/\b(\d{2})\.(\d{2})\.(\d{2}|\d{4})\b/' | текст 20.08.2012 text |
$matches[0] == '20.08.2012' $matches[1] == '20' $matches[2] == '08' $matches[3] == '2012' |
текст 20.08.12 text |
$matches[0] == '20.08.12' $matches[1] == '20' $matches[2] == '08' $matches[3] == '12' |
||
текст 20.08.012 text | $matches[0] == '' | ||
текст 020.08.2012 text | $matches[0] == '' | ||
текст 2.8.12 text | $matches[0] == '' |