PHP RegEx

5 min read

What is a Regular Expression?Тогтмол илэрхийлэл гэж юу вэ? #

A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.

Тогтмол илэрхийлэл бол хайлтын хэв маягийг бүрдүүлдэг тэмдэгтүүдийн дараалал юм. Текстээс өгөгдөл хайхдаа та энэ хайлтын загварыг ашиглан хайж буй зүйлээ тайлбарлах боломжтой.

 

A regular expression can be a single character, or a more complicated pattern.

Тогтмол илэрхийлэл нь ганц тэмдэгт эсвэл илүү төвөгтэй хэв маяг байж болно.

 

Regular expressions can be used to perform all types of text search and text replace operations.

Ердийн хэллэгийг ашиглан бүх төрлийн текст хайх, текст солих үйлдлийг гүйцэтгэхэд ашиглаж болно.


Syntax #

In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers.

PHP дээр ердийн илэрхийлэл нь зааглагч, хэв маяг ба нэмэлт өөрчлөлт оруулагчдаас бүрдэх үг өгүүлбэр юм.

$exp = “/Apprentice/i”;

In the example – Энэ Жишээнд 

above, / is the delimiter, Apprentice is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.

The delimiter can be any character that is not a letter, number, backslash or space. The most common delimiter is the forward slash (/), but when your pattern contains forward slashes it is convenient to choose other delimiters such as # or ~.

Тусгаарлагч нь үсэг, тоо, нурууны ташуу эсвэл зай биш ямар ч тэмдэгт байж болно. Хамгийн нийтлэг зааглагч бол шууд налуу (/) юм, гэхдээ таны хэв маягт налуу ташуу байгаа тохиолдолд # эсвэл ~ гэх мэт бусад зааглагчийг сонгох нь тохиромжтой байдаг.


Regular Expression Functions #

PHP provides a variety of functions that allow you to use regular expressions. The preg_match()preg_match_all() and preg_replace() functions are some of the most commonly used ones:

PHP нь энгийн хэллэгийг ашиглах боломжийг олгодог төрөл бүрийн функцээр хангадаг. Preg_match (), preg_match_all () ба preg_replace () функцууд нь хамгийн түгээмэл хэрэглэгддэг функцууд юм.

Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not

Хэрэв үг өгүүлбэрээс хээ олдсон бол 1-ийг буцааж өгдөг

preg_match_all()

Returns the number of times the pattern was found in the string, which may also be 0

Үг өгүүлбэрээс хээ олдсон тоог буцаана, мөн 0 байж болно

preg_replace()

Returns a new string where matched patterns have been replaced with another string

Таарсан хээг өөр үг өгүүлбэрээр сольсон шинэ мөрийг буцаана


Using preg_match() #

The preg_match() function will tell you whether a string contains matches of a pattern.

preg_match() функц нь үг өгүүлбэрт хээтэй таарч байгаа эсэхийг танд мэдэгдэх болно.

Example #

Жишээ #

Use a regular expression to do a case-insensitive search for “Apprentice” in a string:

Тогтмол илэрхийлэл ашиглан үг өгүүлбэрт “Apprentice” гэсэн тохиолдолд томъёолол, үсгийн хувьд мэдрэмжгүй хайлт хийнэ үү.

<?php $str = "Visit Apprentice"; $pattern = "/Apprentice/i"; echo preg_match($pattern, $str); // Outputs 1 ?>

Using preg_match_all() #

The preg_match_all() function will tell you how many matches were found for a pattern in a string.

preg_match_all() функц нь үг өгүүлбэрт хээтэй хичнээн тохирохыг олж мэдэх болно.

Example #

Жишээ #

Use a regular expression to do a case-insensitive count of the number of occurrences of “ain” in a string:

Тогтмол илэрхийлэл ашиглан үг өгүүлбэрт “аин” -ын тохиолдлын тоог жижиг үсгээр тоолохгүйгээр тоолно уу.

<?php $str = "The rain in SPAIN falls mainly on the plains."; $pattern = "/ain/i"; echo preg_match_all($pattern, $str); // Outputs 4 ?>

Using preg_replace() #

The preg_replace() function will replace all of the matches of the pattern in a string with another string.

Example #

Use a case-insensitive regular expression to replace Microsoft with Apprentice in a string:

<?php $str = "Visit Microsoft!"; $pattern = "/microsoft/i"; echo preg_replace($pattern, "Apprentice", $str); // Outputs "Visit Apprentice!" ?>

Regular Expression Modifiers #

Modifiers can change how a search is performed.

Өөрчлөгч нь хайлт хэрхэн хийгддэгийг өөрчлөх боломжтой.

Modifier Description
i Performs a case-insensitive search

Тохиолдлоос үл хамааран хайлт хийдэг

m Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line)

Олон шугаман хайлт хийдэг (үг өгүүлбэрээс эхлэл эсвэл төгсгөлийг хайж олох загварууд нь мөр бүрийн эхлэл эсвэл төгсгөлтэй тохирч байх болно)

u

Enables correct matching of UTF-8 encoded patterns

UTF-8 кодчилсон хэв маягийг зөв тохируулахыг идэвхжүүлдэг


Regular Expression Patterns #

Brackets are used to find a range of characters:

Хаалтуудыг олон тооны тэмдэгтүүдийг олоход ашигладаг.

Expression Description
[abc] Find one character from the options between the brackets

Хаалт хоорондын сонголтоос нэг тэмдэгт ол

[^abc] Find any character NOT between the brackets

Хаалтны хооронд NOT тэмдэгт олоорой

[0-9]

Find one character from the range 0 to 9

0-ээс 9 хүртэлх хэсгээс нэг тэмдэгт ол

Metacharacters Мэта тэмдэгтүүд

Metacharacters are characters with a special meaning:

Мета тэмдэгтүүд нь онцгой утгатай тэмдэгтүүд юм.

Metacharacter Description
| Find a match for any one of the patterns separated by | as in: cat|dog|fish

| -Ээр тусгаарлагдсан хэв маягийн аль нэгэнд тохирохыг олох шиг: муур | нохой | загас

.

Find just one instance of any character

Аливаа тэмдэгтээс зөвхөн нэг тохиолдлыг олох

^

Finds a match as the beginning of a string as in: ^Hello

Тоглолтыг мөрийн эхлэл болгож дараахь байдлаар олно: ^ Сайн уу

$

Finds a match at the end of the string as in: World$

Мөрний төгсгөлд дараахь зүйлийг тааруулна: World $

\d Find a digit

Цифрийг олох

\s

Find a whitespace character

Хоосон зайны тэмдэгтийг олох

\b

Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b

Иймэрхүү үгийн эхэнд тохирохыг олоорой: \ bWORD, эсвэл дараахь үгийн төгсгөлд: WORD \ b

\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

Xxxx гэсэн арван зургаатын тоогоор тодорхойлогдсон Юникод тэмдэгтийг олоорой

Quantifiers – Тоо  хэмжээ

Quantifiers define quantities:

Тоо хэмжээ нь хэмжигдэхүүнийг тодорхойлно.

Quantifier Description
n+ Matches any string that contains at least one n

Наад зах нь нэг n агуулсан мөртэй таарч тохирно

n* Matches any string that contains zero or more occurrences of n

N-ийн тэг ба түүнээс дээш тохиолдлыг агуулсан мөртэй таарч тохирно

n? Matches any string that contains zero or one occurrences of n

Н -ньТэг эсвэл нэг тохиолдлыг агуулсан мөртэй таарч тохирно

n{x} Matches any string that contains a sequence of X n‘s

X n-ийн дарааллыг агуулсан дурын мөртэй таарч тохирно

n{x,y}

Matches any string that contains a sequence of X to Y n‘s

X-ээс Y n-ийн дарааллыг агуулсан дурын мөртэй таарч тохирно

n{x,}

Matches any string that contains a sequence of at least X n‘s

Хамгийн багадаа X n-ийн дарааллыг агуулсан мөртэй таарч тохирно

Note: If your expression needs to search for one of the special characters you can use a backslash ( \ ) to escape them. For example, to search for one or more question marks you can use the following expression: $pattern = ‘/\?+/’;

Тэмдэглэл: Хэрэв таны илэрхийлэлд тусгай тэмдэгтүүдийн аль нэгийг хайх шаардлагатай бол тэдгээрээс зугтахын тулд налуу (\) тэмдэг ашиглаж болно. Жишээлбэл, нэг буюу хэд хэдэн асуултын тэмдгийг хайхдаа дараахь илэрхийлэлийг ашиглаж болно: $ pattern = ‘/ \? + /’;


Grouping #

You can use parentheses ( ) to apply quantifiers to entire patterns. They also can be used to select parts of the pattern to be used as a match.

Хэмжээг бүхэлд нь хэвэнд хэрэглэхдээ хаалтыг ( )ашиглаж болно. Эдгээрийг тохирох хэлбэрээр ашиглах загварын хэсгүүдийг сонгоход ашиглаж болно.

Example #

Жишээ #

Use grouping to search for the word “banana” by looking for ba followed by two instances of na:

“banana” гэсэн үгийг хайхдаа бүлэглэлийг ашиглан ba-г хайгаад на гэсэн хоёр тохиолдлыг ашиглаарай.

<?php $str = "Apples and bananas."; $pattern = "/ba(na){2}/i"; echo preg_match($pattern, $str); // Outputs 1 ?>

Complete RegExp Reference #

For a complete reference, go to our Complete PHP Regular Expression Reference.

Бүрэн лавлагаа авахын тулд манай PHP-ийн Regular Expression лавлагаа руу орно уу.

The reference contains descriptions and examples of all Regular Expression functions.

Лавлагаа нь бүх ердийн илэрхийлэх функцүүдийн тодорхойлолт, жишээг агуулдаг.

Powered by BetterDocs

Leave a Reply