Регулярные выражения php

Pattern Modifiers

A pattern modifier allows you to control the way a pattern match is handled. Pattern modifiers are placed directly after the regular expression, for example, if you want to search for a pattern in a case-insensitive manner, you can use the modifier, like this: . The following table lists some of the most commonly used pattern modifiers.

Modifier What it Does
Makes the match case-insensitive manner.
Changes the behavior of and to match against a newline boundary (i.e. start or end of each line within a multiline string), instead of a string boundary.
Perform a global match i.e. finds all occurrences.
Evaluates the expression only once.
Changes the behavior of (dot) to match all characters, including newlines.
Allows you to use whitespace and comments within a regular expression for clarity.

The following example will show you how to perform a global case-insensitive search using the modifier and the PHP function.

Similarly, the following example shows how to match at the beginning of every line in a multi-line string using anchor and modifier with PHP function.

Non-Printable Characters

You can use special character sequences to put non-printable characters in your regular expression. Use \t to match a tab character (ASCII 0x09), \r for carriage return (0x0D) and \n for line feed (0x0A). More exotic non-printables are \a (bell, 0x07), \e (escape, 0x1B), \f (form feed, 0x0C) and \v (vertical tab, 0x0B). Remember that Windows text files use \r\n to terminate lines, while UNIX text files use \n.

If your application supports Unicode, use \uFFFF or \x{FFFF} to insert a Unicode character. \u20AC or \x{20AC} matches the euro currency sign.

If your application does not support Unicode, use \xFF to match a specific character by its hexadecimal index in the character set. \xA9 matches the copyright symbol in the Latin-1 character set.

All non-printable characters can be used directly in the regular expression, or as part of a character class.

Слияние нескольких диапазонов

Предопределенные классы символов

регулярных выражениях

  • : Цифра. Эквивалентно .
  • : Нецифровой символ. Эквивалентно .
  • : Пробельный символ. Эквивалентно .
  • : Не пробельный символ. Эквивалентно .
  • : Словообразующий символ. Эквивалентно .
  • : Не словообразующий символ. Эквивалентно .
Разделители строк
Документация по SDK класса описывает метасимвол точки как предопределенный класс символов, соответствующий любому символу, кроме разделителей строк (одно- или двухсимвольные последовательности, отмечающие конец строки). Исключение составляет режим dotall (который мы обсудим далее), в котором точка соответствуют и разделителям строк. Класс различает следующие разделители строк:

  • cимвол возврата каретки ();
  • cимвол новой строки (символ протяжки бумаги на одну строку) ();
  • cимвол возврата каретки, за которым непосредственно следует символ новой строки ();
  • cимвол следующей строки ();
  • cимвол разделения строк ();
  • cимвол разделения абзацев ()

Граничные сопоставители

  • : Начало строки;
  • : Конец строки;
  • : Граница слова;
  • : Граница псевдослова;
  • : Начало текста;
  • : Конец предыдущего совпадения;
  • : Конец текста, не считая итогового разделителя строк (если таковой присутствует);
  • : Конец текста

Квантификаторы

  • Жадный квантификатор (, или ) предназначен для поиска самого длинного совпадения. Можно задать ? для поиска одного или менее вхождений , для поиска нуля или более вхождений , для поиска одного или более вхождений , для поиска вхождений , для поиска не менее (а возможно, и более) вхождений и для поиска не менее , но не более вхождений .
  • Ленивый квантификатор (, или ) предназначен для поиска самого короткого совпадения. Можно задать для поиска одного или менее вхождений , ? для поиска нуля или более вхождений , для поиска одного или более вхождений , для поиска вхождений , для поиска не менее (а возможно, и более) вхождений и для поиска не менее , но не более вхождений .
  • Сверхжадный квантификатор (, или ) аналогичен жадному, за исключением того, что сверхжадный квантификатор выполняет только одну попытку найти самое длинное совпадение, в то время как жадный может выполнять несколько попыток. Можно задать для поиска одного или менее вхождений , для поиска нуля или более вхождений , для поиска одного или более вхождений , для поиска вхождений , для поиска не менее (а возможно, и более) вхождений и для поиска не менее , но не более вхождений .

Вложенные флаговые выражения

  • : активирует нечувствительный к регистру поиск по шаблону. Например, при использовании команды последовательность символов соответствует шаблону . По умолчанию используется поиск по шаблону с учетом регистра.
  • : разрешает использование внутри шаблона пробельных символов и комментариев, начинающихся с метасимвола . Сопоставитель будет игнорировать и те, и другие. Например, для последовательность символов соответствует шаблону . По умолчанию, пробельные символы и комментарии запрещены, сопоставитель рассматривает их как символы, участвующие в поиске.
  • : активирует режим dotall, в котором метасимвол точки соответствует разделителям строк, помимо любого другого символа. Например, при команде будет найден символ новой строки. По умолчанию используется противоположный dotall режим: разделители строк не будут находиться. Например, при команде символ новой строки найден не будет.
  • : активирует многострочный режим, при котором соответствует началу, а – концу каждой строки. Например, находит во входном тексте обе последовательности . По умолчанию используется однострочный режим: соответствует началу всего входного текста, а — его концу. Например, возвращает ответ об отсутствии совпадений.
  • : активирует выравнивание регистра с учетом Unicode. Этот флаг, при совместном использовании с , позволяет осуществлять поиск по шаблону без учета регистра в соответствии со стандартом Unicode. Настройка по умолчанию — поиск с учетом регистра и только по символам из набора US-ASCII.
  • : активирует режим строк в стиле Unix, при котором сопоставитель распознает в контексте метасимволов , и только разделитель строк . По умолчанию используется режим строк в стиле не-Unix: сопоставитель распознает в контексте вышеупомянутых метасимволов все разделители строк.
Указание нескольких вложенных флаговых выражений
Существует возможность указания нескольких вложенных флаговых выражений в регулярном выражении путем или расположения их бок о бок (), или размещения последовательно определяющих их букв ().

Positive and Negative Lookahead

Negative lookahead is indispensable if you want to match something not followed by something else. When explaining character classes, this tutorial explained why you cannot use a negated character class to match a q not followed by a u. Negative lookahead provides the solution: q(?!u). The negative lookahead construct is the pair of parentheses, with the opening parenthesis followed by a question mark and an exclamation point. Inside the lookahead, we have the trivial regex u.

Positive lookahead works just the same. q(?=u) matches a q that is followed by a u, without making the u part of the match. The positive lookahead construct is a pair of parentheses, with the opening parenthesis followed by a question mark and an equals sign.

You can use any regular expression inside the lookahead (but not lookbehind, as explained below). Any valid regular expression can be used inside the lookahead. If it contains capturing groups then those groups will capture as normal and backreferences to them will work normally, even outside the lookahead. (The only exception is Tcl, which treats all groups inside lookahead as non-capturing.) The lookahead itself is not a capturing group. It is not included in the count towards numbering the backreferences. If you want to store the match of the regex inside a lookahead, you have to put capturing parentheses around the regex inside the lookahead, like this: (?=(regex)). The other way around will not work, because the lookahead will already have discarded the regex match by the time the capturing group is to store its match.

Синтаксис регулярных выражений

1. Метасимволы для поиска совпадений границ строк или текста

Метасимвол Назначение
^ начало строки
$ конец строки
\b граница слова
\B не граница слова
\A начало ввода
\G конец предыдущего совпадения
\Z конец ввода
\z конец ввода

2. Метасимволы для поиска символьных классов

Метасимвол Назначение
\d цифровой символ
\D нецифровой символ
\s символ пробела
\S непробельный символ
\w буквенно-цифровой символ или знак подчёркивания
\W любой символ, кроме буквенного, цифрового или знака подчёркивания
. любой символ

3. Метасимволы для поиска символов редактирования текста

Метасимвол Назначение
\t символ табуляции
\n символ новой строки
\r символ возврата каретки
\f переход на новую страницу
\u 0085 символ следующей строки
\u 2028 символ разделения строк
\u 2029 символ разделения абзацев

4. Метасимволы для группировки символов

Метасимвол Назначение
любой из перечисленных (а,б, или в)
любой, кроме перечисленных (не а,б, в)
слияние диапазонов (латинские символы от a до z без учета регистра )
] объединение символов (от a до d и от m до p)
] пересечение символов (символы d,e,f)
] вычитание символов (символы a, d-z)

5. Метасимволы для обозначения количества символов – квантификаторы. Квантификатор всегда следует после символа или группы символов.

Метасимвол Назначение
? один или отсутствует
* ноль или более раз
+ один или более раз
{n} n раз
{n,} n раз и более
{n,m} не менее n раз и не более m раз

Daha fazlası

İfade gruplarını yakalamamak

Yukarıda özellikle yakalamak istediğimiz ifadeleri parantez içine almamız gerektiğini söylemiştim. Fakat her parantez içine aldığımızı yakalamak istemeyebiliriz. Bunun için parantezleri şeklinde kullanabiliriz.

Böylece bu parantezin yakaladığı içerik sadece çalışırken kullanılır, sonuçta gösterilmez.

/(w+@w+(?:.w+)+)/

İfade gruplarını isimlendirme

Yukarıdaki örnekte gereksiz parantezleri almayıp elde ettiğimiz sonucu biraz daha düzene sokmuş olduk. Şimdi ise bu gruba isim vererek daha da düzeni sağlayabiliriz.

Grupları şeklinde isimlendirebilirsiniz.

$pattern = '/(?<email>w+@w+(?:.w+)+)/i';
$content = 'Bir kaç adres: elma@manav.com, yarimkilo@kasap.com, ates@askeriye.com';

preg_match_all($pattern, $content, $results);

print_r($results);
Array
(
     => elma@manav.com
     => yarimkilo@kasap.com
     => ates@askeriye.com
)

Hiç dizi elemanlarının hangisi benim ihtiyacım olandı diye uğraşmadan direkt isim verdiğimiz grubun yakaladığı içeriklere ulaşabiliriz.

Hava durumu

Yine pratik bir örnek ile meteoroloji sitesinden İstanbul için günlük hava durumunu yakalayan bir desen hazırlayalım. Bu tür işlerin püf noktası aradığımız içeriği çevreleyen eşsiz desenleri görmek.

Sayfanın kaynağını açıp aradığımız sıcaklığın hangi HTML etiketleri arasında olduğuna bakıyoruz.

$content = file_get_contents('http://www.mgm.gov.tr/tahmin/il-ve-ilceler.aspx?m=ISTANBUL');

// Derece
preg_match_all('/<em class="renkMin zemimeZ">(.+)C</em></td>/si', $content, $results);
// İlk eşleşeni alıyoruz
$degree = $results;

// Hava durumunun ikonu ve açıklaması
preg_match_all('/"(+)" rowspan="2"><img src="..([w/.-]+)"/si', $content, $results);
$description = $results;
$image = 'http://www.mgm.gov.tr' . $results;

echo $degree . ' ' . $description;
echo '<img src="' . $image . '" />';

Ekranda hava durumunu görürüz.

Daha yeni başlıyoruz

Aşağıdaki faydalı kaynakları da inceleyip kurcalamanızı öneriyorum.

Konu hakkında aklınıza takılan, sormak istediğiniz ya da nasıl yaparım dediğiniz şeyleri yorum yazarak sormaktan çekinmeyin.

Bir başka PHP serüveninde görüşmek üzere kendinize iyi bakın!

Regular Expression — Documentation

Metacharacters

Character What does it do?
\
  • Used to indicate that the next character should NOT be interpreted literally. For example, the character ‘w’ by itself will be interpreted as
    ‘match the character w’, but using ‘\w’ signifies ‘match an alpha-numeric character including underscore’.
  • Used to indicate that a metacharacter is to be interpreted literally. For example, the ‘.’ metacharacter means ‘match any single character but a new line’, but if
    we would rather match a dot character instead, we would use ‘\.’.
^
  • Matches the beginning of the input. If in multiline mode, it also matches after a line break character, hence every new line.
  • When used in a set pattern (), it negates the set; match anything not enclosed in the brackets
$ Matches the end of the input. If in multiline mode, it also matches before a line break character, hence every end of line.
* Matches the preceding character 0 or more times.
+ Matches the preceding character 1 or more times.
?
  • Matches the preceding character 0 or 1 time.
  • When used after the quantifiers *, +, ? or {}, makes the quantifier non-greedy; it will match
    the minimum number of times as opposed to matching the maximum number of times.
. Matches any single character except the newline character.
(x) Matches ‘x’ and remembers the match. Also known as capturing parenthesis.
(?:x) Matches ‘x’ but does NOT remember the match. Also known as NON-capturing parenthesis.
x(?=y) Matches ‘x’ only if ‘x’ is followed by ‘y’. Also known as a lookahead.
x(?!y) Matches ‘x’ only if ‘x’ is NOT followed by ‘y’. Also known as a negative lookahead.
x|y Matches ‘x’ OR ‘y’.
{n} Matches the preceding character exactly n times.
{n,m} Matches the preceding character at least n times and at most m times. n and m can be omitted if zero..
Matches any of the enclosed characters. Also known as a character set.
You can create range of characters using the hyphen character such as A-Z (A to Z). Note that in character sets,
special characters (., *, +) do not have any special meaning.
Matches anything NOT enclosed by the brackets. Also known as a negative character set.
Matches a backspace.
\b Matches a word boundary. Boundaries are determined when a word character is NOT followed or NOT preceeded with another word character.
\B Matches a NON-word boundary. Boundaries are determined when two adjacent characters are word characters OR non-word characters.
\cX Matches a control character. X must be between A to Z inclusive.
\d Matches a digit character. Same as or .
\D Matches a NON-digit character. Same as or .
\f Matches a form feed.
\n Matches a line feed.
\r Matches a carriage return.
\s Matches a single white space character. This includes space, tab, form feed and line feed.
\S Matches anything OTHER than a single white space character. Anything other than space, tab, form feed and line feed.
\t Matches a tab.
\v Matches a vertical tab.
\w Matches any alphanumeric character incuding underscore. Equivalent to .
\W Matches anything OTHER than an alphanumeric character incuding underscore. Equivalent to .
\x A back reference to the substring matched by the x parenthetical expression. x is a positive integer.
\0 Matches a NULL character.
\xhh Matches a character with the 2-digits hexadecimal code.
\uhhhh Matches a character with the 4-digits hexadecimal code.

The \G Assertion

The \G assertion allows you to continue searching from the point where the last match occurred. For example, in the following code, we have used \G so that we can search to the correct position and then extract some information, without having to create a more complex, single regular expression −

#!/usr/bin/perl

$string = "The time is: 12:31:02 on 4/12/00";

$string =~ /:\s+/g;
($time) = ($string =~ /\G(\d+:\d+:\d+)/);
$string =~ /.+\s+/g;
($date) = ($string =~ m{\G(\d+/\d+/\d+)});

print "Time: $time, Date: $date\n";

When above program is executed, it produces the following result −

Time: 12:31:02, Date: 4/12/00

The \G assertion is actually just the metasymbol equivalent of the pos function, so between regular expression calls you can continue to use pos, and even modify the value of pos (and therefore \G) by using pos as an lvalue subroutine.

Regular-expression Examples

Character Classes

Sr.No. Example & Description
1

ython

Matches «Python» or «python»

2

rub

Matches «ruby» or «rube»

3

Matches any one lowercase vowel

4

Matches any digit; same as

5

Matches any lowercase ASCII letter

6

Matches any uppercase ASCII letter

7

Matches any of the above

8

Matches anything other than a lowercase vowel

9

Matches anything other than a digit

Special Character Classes

Sr.No. Example & Description
1

.

Matches any character except newline

2

\d

Matches a digit:

3

\D

Matches a nondigit:

4

\s

Matches a whitespace character:

5

\S

Matches nonwhitespace:

6

\w

Matches a single word character:

7

\W

Matches a nonword character:

Repetition Cases

Sr.No. Example & Description
1

ruby?

Matches «rub» or «ruby»: the y is optional

2

ruby*

Matches «rub» plus 0 or more ys

3

ruby+

Matches «rub» plus 1 or more ys

4

\d{3}

Matches exactly 3 digits

5

\d{3,}

Matches 3 or more digits

6.

\d{3,5}

Matches 3, 4, or 5 digits

Nongreedy Repetition

This matches the smallest number of repetitions −

Sr.No. Example & Description
1

<.*>

Greedy repetition: matches «<python>perl>»

2

<.*?>

Nongreedy: matches «<python>» in «<python>perl>»

Grouping with Parentheses

Sr.No. Example & Description
1

\D\d+

No group: + repeats \d

2

(\D\d)+

Grouped: + repeats \D\d pair

3

(ython(, )?)+

Match «Python», «Python, python, python», etc.

Backreferences

This matches a previously matched group again −

Sr.No. Example & Description
1

()ython&\1ails

Matches python&pails or Python&Pails

2

()*\1

Single or double-quoted string. \1 matches whatever the 1st group matched. \2 matches whatever the 2nd group matched, etc.

Alternatives

Sr.No. Example & Description
1

python|perl

Matches «python» or «perl»

2

rub(y|le))

Matches «ruby» or «ruble»

3

Python(!+|\?)

«Python» followed by one or more ! or one ?

Anchors

This need to specify match positions.

Sr.No. Example & Description
1

^Python

Matches «Python» at the start of a string or internal line

2

Python$

Matches «Python» at the end of a string or line

3

\APython

Matches «Python» at the start of a string

4

Python\Z

Matches «Python» at the end of a string

5

\bPython\b

Matches «Python» at a word boundary

6

\brub\B

\B is nonword boundary: match «rub» in «rube» and «ruby» but not alone

7

Python(?=!)

Matches «Python», if followed by an exclamation point

8

Python(?!!)

Matches «Python», if not followed by an exclamation point

Special Syntax with Parentheses

Sr.No. Example & Description
1

R(?#comment)

Matches «R». All the rest is a comment

2

R(?i)uby

Case-insensitive while matching «uby»

3

R(?i:uby)

Same as above

4

rub(?:y|le))

Group only without creating \1 backreference

Previous Page
Print Page

Next Page  

Perl regular expression with quantifiers

In the previous examples, we have created regular expressions by simply putting the characters we want to match between a pair of forward slashes. What if you want to find the same sequence of characters multiple times? you may quickly write something like:

How about 100 times or more? Fortunately, regular expression engine provides you with quantifiers to build such kind of patterns. For example, to find match 100 times in a text, you could do it as follows:

The following table provides some useful quantifiers:

Quantifier Meaning
A* Zero or more A
A+ One or more A
X? A is optional
A{10} Ten A
A{1,5} From one to five A
A{2,} Two A or more

Let’s take a look at the following example:

The regular expression means zero or more followed by at least one or more , therefore, the output is:

Up to now you’ve noticed that the regular expression engine treats some characters in a special way. These characters are called metacharacters. The following are the metacharacters in Perl regular expressions:

To match the literal version of those characters, you have to a backslash \ in front of them in the regular expressions.

In this tutorial, we have introduced you to some techniques to match strings of text using Perl regular expression including basic matching, case-insensitive matching and quantifiers.

  • Was this tutorial helpful ?

Kategoriler

  • ►Genel (9)

  • ►Başlangıç (10)

  • ▼İleri (3)

    • PHP Data Objects (PDO)
    • PDO MySQL veritabanı sınıfı
    • PHP ile regular expression (regex)
  • ►Orta (21)

  • ►Temel Bilgiler (7)

  • PHP 5.4 ile gelen yeni özellikler
  • phpr.org WordPress teması!
  • En iyi PHP editörleri
  • PHP dersleri
  • PHP serüvenleri Twitter\’da!
  • Neden blog yazmalısınız?
  • PHPKonf 2016
  • PHP mi ASP.NET mi?
  • PHP değişkenleri
  • PHP sabitleri
  • PHP dizileri (Array)
  • PHP Cookie (Çerezler)
  • PHP Session (Oturum yönetimi)
  • PHP veri türleri
  • PHP ifadeleri ve operatörleri
  • PHP döngüleri (While, for, foreach, do … while)
  • PHP fonksiyon kullanımı ve örnekleri
  • PHP ile checkbox kullanımı
  • PHP Data Objects (PDO)
  • PDO MySQL veritabanı sınıfı
  • PHP ile regular expression (regex)
  • PHP form kullanımı ve örnekleri
  • Faydalı PHP fonksiyonları
  • PHP orta seviye konuları
  • PHP dosya sistemi işlevleri
  • PHP dizin işlemleri
  • PHP ile dosya upload
  • PHP MYSQL bağlantısı yapmak
  • PHP istisna yönetimi
  • PHP mail formu yapımı
  • PHP r n t karakterleri
  • PHP ile ajax
  • PHP bot yapımı
  • PHP class (sınıf) yapısı
  • PHP çoklu dil desteği
  • PHP veritabanı sınıfı
  • Resimli mail ile aktivasyon
  • CodeIgniter Controller/Method adına göre cache gruplandırma
  • PHP htaccess kullanımı
  • PHP ile sayfalama
  • PHP ile SMTP\’den mail gönderme
  • PHP ile tarih ve saat
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector