Delimiters
When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.
Often used delimiters are forward slashes (/), hash signs (#) and tildes (~). The following are all examples of valid delimited patterns.
/foo bar/ #^[^0-9]$# +php+ %[a-zA-Z0-9_-]%
If the delimiter needs to be matched inside the pattern it must be escaped using a backslash. If the delimiter appears often inside the pattern, it is a good idea to choose another delimiter in order to increase readability.
/http:\/\// #http://#
In addition to the aforementioned delimiters, it is also possible to use bracket style delimiters where the opening and closing brackets are the starting and ending delimiter, respectively.
{this is a pattern}
You may add pattern modifiers after the ending delimiter. The following is an example of case-insensitive matching:
#[a-z]#i
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Обработка текста
- Функции для работы с регулярными выражениями (Perl-совместимые)
- Регулярные выражения PCRE
- Вступление
- Разделители
- Метасимволы
- Экранирующие последовательности
- Свойства Unicode-символов
- Якоря
- Метасимвол точка
- Символьные классы
- Альтернативный выбор
- Установка внутренних опций
- Подмаски
- Повторение
- Обратные ссылки
- Утверждения
- Однократные подмаски
- Условные подмаски
- Комментарии
- Рекурсивные шаблоны
- Производительность
Коментарии
Note that bracket style opening and closing delimiters aren't a 100% problem-free solution, as they need to be escaped when they aren't in matching pairs within the expression. That mismatch can happen when they appear inside character classes [...], as most meta-characters lose their special meaning. Consider these examples:
<?php
preg_match('{[{]}', ''); // Warning: preg_match(): No ending matching delimiter '}'
preg_match('{[}]}', ''); // Warning: preg_match(): Unknown modifier ']'
preg_match('{[}{]}', ''); // Warning: preg_match(): Unknown modifier ']'
?>
Escaping them solves it:
<?php
preg_match('{[\{]}', ''); // OK
preg_match('{[}]}', ''); // OK
preg_match('{[\}\{]}', ''); // OK
?>
preg_match('{[}]}', ''); // Warning: preg_match(): Unknown modifier ']'
preg_match('{[\}]}', ''); // OK
Note that angle brackets `<>` shouldn't be used as delimiters whenever you will have to invoke advanced clusters like atomic groups or lookbehinds because their including angle bracket doesn't come in pair and escaping doesn't help either.