15.08.2023

php regular. Regular Expressions in PHP. Checking credit card numbers


In today's article, we'll take a look at regular expressions in PHP and also see practical examples of using regular expressions in PHP scripts.

Regular Expression Basics in PHP

At the very beginning of the advent of regular expressions, they were entrusted with the task of helping with working with strings in Unix systems. Later, they began to be actively used not only in other systems, but also in different programming languages.

PHP uses regular expressions to parse text according to a certain pattern. Using regular expressions, you can easily find the desired text in a string using a pattern, and replace it if necessary, or simply check for the presence of such text.

Regular expression types

There are 2 types of regular expressions:

  • Perl compatible
  • POSIX extended

Perl compatible functions are like preg_match , preg_replace , and POSIX versions like ereg , eregi . Please note that the latest features are deprecated in PHP 5.3.0 and have been removed in . Therefore, we will only use Perl compatible functions. It is important to know that when using Perl-compatible regular expressions, such an expression must be enclosed in delimiters, such as forward slashes (/).

Basic Regular Expression Syntax in PHP

To use regular expressions, you first need to learn the pattern syntax. We can group characters within a pattern like this:

  • Regular characters that follow one another, like hello
  • Line start and end indicators in the form of ^ and $
  • Count indicators such as + , * , ?
  • Logical operators such as |
  • Grouping operators such as () , () ,

An example regular expression pattern for validating an email address is as follows:

The PHP code for email validation using a Perl compatible regular expression is as follows:

Now let's look at a detailed analysis of the pattern syntax with a regular expression:

Regular expression (pattern) Passing test (object) Fails validation (object) A comment
world hello world Hello Ivan Passes if the pattern is present anywhere in the object
^world world class hello world Passes if the pattern is present at the beginning of the object
world$ hello world world class Passes if the pattern is present at the end of the object
world/i This WoRLd Hello Ivan Performs searches in case insensitive mode
^world$ world hello world The string only contains "world"
world* worl, world, worlddd wor There are 0 or more "d" after "worl"
world+ world, worlddd world There is at least one "d" after "worl"
world? worl, world, worly wor, wory There are 0 or 1 "d" after "worl"
world(1) world worthy There is one "d" after "worl"
world(1,) world, worlddd worthy There is one or more "d" after "worl"
world(2,3) worldd, worlddd world There are 2 or 3 "d" after "worl"
wo(rld)* wo, world, world old wa There are 0 or more "rld" after "wo"
earth|world earth, world sun The string contains "earth" or "world"
w.rld world, wwrld wrld Contains any character instead of a dot
^.{5}$ world, earth sun The string contains exactly 5 characters
abc, bbaccc sun There is "a" or "b" or "c" in the string
world WORLD The string contains any lowercase letters
world, WORLD, World12 123 The string contains any lowercase or uppercase letters
[^wW] earth w, W The actual character cannot be "w" or "W"

Now let's move on to a more complex regular expression with a detailed explanation.

Practical Examples of Complex Regular Expressions

Now that you know the theory and basic syntax of regular expressions in PHP, it's time to create and analyze some more complex examples.

1) Validate username with regular expression
Let's start by checking the username. If you have a signup form, you will need to validate usernames. Suppose you don't want any special characters other than " _.- " in the name and of course the name must contain letters and possibly numbers. Also, you may need to control the length of the username, for example between 4 and 20 characters.

First we need to define the available characters. This can be implemented with the following code:

After that, we need to limit the number of characters with the following code:

Now putting this regular expression together:

^{4,20}$

For a Perl compatible regular expression, enclose it with ' / '. The final PHP code looks like this:

2) Validate hex color code with regular expression
The hexadecimal color code looks like this: #5A332C , it is also possible to use a short form, for example #C5F . In both cases, the color code starts with # and then exactly 3 or 6 numbers or letters from a before f.

So let's check the beginning of the code:

^#

Then we check the range of valid characters:

After that, we check the allowable code length (it can be either 3 or 6). The full code of the regular expression will be as follows:

^#(({3}$)|({6}$))

Here we use a logical operator to first check the code of the form #123 and then the code of the form #123456 . The final PHP code for checking with a regular expression looks like this:

3) Validate customer email using regular expression
Now let's see how we can validate an email address using regular expressions. First, carefully consider the following examples of email addresses:

[email protected] [email protected] [email protected]

As we can see, the @ symbol is a required element in an email address. In addition, there must be some set of characters before and after this element. More precisely, it must be followed by a valid domain name.

So the first part should be a string with letters, numbers, or some special characters like _-. . In a template, we can write it like this:

^+

A domain name always has, say, name and tld ( top level domain) – i.e. domain zone. The domain zone is .com , .ua , .info and the like. This means that the regex pattern for the domain will look like this:

+\.{2,5}$

Now, if we put everything together, we get the full regex pattern for validating an email address:

^+@+\.{2,5}$

In PHP code, this check would look like this:

We hope that today's article has helped you get familiar with regular expressions in PHP, and practical examples will be useful for you when using regular expressions in your own PHP scripts.

When working with texts in any modern programming language, developers are constantly faced with the tasks of checking the entered data for compliance with the desired pattern, searching and replacing test fragments, and other typical operations for processing symbolic information. Development of own verification algorithms leads to loss of time, incompatibility of the program code and complexity in its development and modernization.

The rapid development of the Internet and WEB development languages ​​required the creation of universal and compact tools for processing text information with a minimum amount of code required for this. The PHP language, popular among beginners and professional developers, is no exception. The regular expression as a text template language allows you to simplify the tasks of text processing and reduce the program code by tens and hundreds of lines. Many tasks are generally impossible to solve without it.

Regular Expressions in PHP

The PHP language contains three mechanisms for working with regular expressions - "ereg", "mb_ereg" and "preg". The most common is the "preg" interface, whose functions provide access to the PCRE regular expression support library, originally developed for the Perl language, which is bundled with PHP. Preg functions look for matches in a given text string, according to a specific pattern in the regular expression language.

Syntax Basics

Within the framework of a short article, it is impossible to describe in detail the entire syntax of regular expressions; there is a special literature for this. We will only give the main elements to show the wide possibilities for the developer and understand the code examples.

B is formally defined very difficult, and therefore we will simplify the description. The regular expression is a text string. It consists of a delimited pattern and a modifier indicating how to process it. It is possible to include various alternatives and repetitions in the templates.

For example, in the expression /\d(3)-\d(2)-\d(2)/m the delimiter will be «/» , followed by the pattern, and the symbol "m" will be a modifier.

The full power of regular expressions is encoded with metacharacters. The main metacharacter of the language is the backslash - "\". It reverses the type of the character that follows it (i.e., a regular character becomes a metacharacter and vice versa). Another important metacharacter is the forward slash "|", which specifies alternate patterns. More examples of metacharacters:

PHP, when processing regular expressions, treats a space as a separate significant character, so the expressions ABCWHERE and ABCWHERE are different.

Subpatterns

In PHP, regular subpatterns are distinguished by parentheses and are sometimes referred to as "subexpressions". Perform the following functions:

    Selection of alternatives. For example, template heat(some|bird|) matches the words "heat", "firebird" And "roast". And without brackets, it will be just an empty string, "bird" and "hot".

    "Exciting" subpattern. This means that if a substring matches in the pattern, then all matches are returned as a result. For clarity, let's take an example. Given the following regular expression: the winner receives ((gold|gilded)(medal|cup)) - and a string to search for matches: "winner gets gold medal". In addition to the original phrase, the search will result in: "gold medal", "medal", "gold".

Repetition operators (quadifiers)

When compiling regular expressions, it is very often necessary to analyze repetitions of numbers and characters. This is not a problem if there are not very many repetitions. But what to do when we do not know their exact number? In this case, special metacharacters must be used.

To describe repetitions, quadrifiers are used - metacharacters to set the quantity. Quadifiers are of two types:

  • general, enclosed in brackets;
  • abbreviated.

The general quantifier specifies the minimum and maximum number of allowed repetitions of the element as two numbers in curly braces, like this: x(2.5). If the maximum number of repetitions is unknown, the second argument is omitted: x(2,).

The abbreviated quantifiers are symbols for the most common repetitions to avoid overloading the syntax. Three abbreviations are commonly used:

1. * - zero or more repetitions, which is equivalent to (0,).

2. + - one or more repetitions, i.e.,).

3.? - zero or only one repetition - (0.1).

Regular expression examples

For those who are learning regular expressions, the examples are the best tutorial. Here are a few that show their great potential with a minimum of effort. All programming codes are fully compatible with PHP versions 4.x and higher. For a complete understanding of the syntax and using all the features of the language, we recommend the book Regular Expressions by J. Friedl, where the syntax is fully covered and there are examples of regular expressions not only in PHP, but also for Python, Perl, MySQL, Java, Ruby and C#.

Checking the correctness of the E-mail address

Task. There is a web page that asks the visitor for an email address. The regular expression should check if the received address is correct before sending the messages. The check does not guarantee that the specified mailbox really exists and accepts letters. But she can weed out deliberately wrong addresses.

Solution. As with any programming language, email address validation regular expressions can be implemented in PHP in a variety of ways, and the examples in this article are not meant to be definitive or the only way. Therefore, in each case, we will provide a list of requirements that must be taken into account when programming, and the specific implementation is completely dependent on the developer.

So, the expression that checks the validity of the email should check the following conditions:

  1. The presence of the @ symbol in the source string and the absence of spaces.
  2. The domain part of the address, after the @ symbol, contains only valid characters for domain names. The same applies to the username.
  3. When validating a username, it is necessary to detect the presence of special characters, such as the apostrophe or the apostrophe. These characters are potentially dangerous and can be contained in attacks such as SQL injections. Avoid such addresses.
  4. Usernames allow only one dot, which cannot be the first or last character in a string.
  5. The domain name must contain at least two and no more than six characters.

An example that takes into account all these conditions can be seen in the figure below.

Validate URLs

Task. Check if a given text string is valid Again, URL validation regular expressions can be implemented in a variety of ways.

Solution. Our final version looks like this:

/^(https?:\/\/)?([\da-z\.-]+)\.((2,6))([\/\w \.-]*)*\/?$ /

Now let's analyze its components in more detail, using the figure.

Checking credit card numbers

Task. It is necessary to implement verification of the correctness of the entered plastic card number of the most common payment systems. Map only option considered

Solution. When creating an expression, it is necessary to take into account the possible presence of spaces in the entered number. The digits of the number on the card are divided into groups for easier reading and dictation. Therefore, it is only natural that a person might try to enter a number in this way (i.e. using spaces).

Writing a generic expression that takes into account possible spaces and hyphens is more difficult than simply discarding all characters except numbers. Therefore, it is recommended to use the /D metacharacter in the expression, which removes all characters except digits.

Now you can go directly to checking the number. All credit card companies use a unique number format. The example uses this, and the client does not need to enter the company name - it is determined by the number. Visa cards always start with 4 and are 13 or 16 digits long. MasterCard starts in the range 51-55 with a number length of 16. As a result, we get the following expression:

Before processing the order, you can additionally check the last digit of the number, which is calculated using the Luhn algorithm.

Checking phone numbers

Task. Checking the correctness of the entered phone number.

Solution. The number of digits in landline and mobile phone numbers varies considerably from country to country, so it is not possible to universally validate a phone number using regular expressions. But international numbers have a strict format and are great for pattern checking. Moreover, more and more national telephone operators are trying to comply with a single standard. The structure of the number is as follows:

+CCC.NNNNNNNNNNxEEEE, Where:

C is a 1-3 digit country code.

N - number up to 14 digits long.

E is an optional extension.

The plus sign is a required element, and the x sign is present only when an extension is needed.

As a result, we have the following expression:

^\+(1,3)\.(4,14)(?:x.+)?$

Numbers in a range

Task. It is necessary to ensure that an integer from a certain range matches. Additionally, it is necessary that regular expressions find only numbers from a range of values.

Solution. Here are some expressions for some of the most common cases:

IP address lookup

Task. You must determine if the given string is a valid IP address in IPv4 format in the range 000.000.000.000-255.255.255.255.

Solution. As with any PHP task, a regular expression has many variations. For example, this:

Online check of expressions

Checking regular expressions for correctness can be difficult for novice programmers due to the complexity of the syntax, which differs from "regular" programming languages. To solve this problem, there are many online expression testers that make it easy to check the correctness of the created template on real text. The programmer enters an expression and data for verification and instantly sees the result of processing. Usually there is also a reference section, which describes in detail regular expressions, examples and implementation differences for the most common programming languages.

But fully trusting the results of online services is not recommended for all developers using PHP. A regular expression written and personally tested improves skills and ensures that there are no errors.

Regular expressions are special patterns for searching for a substring in text. With their help, you can solve such problems in one line: “check if the string contains numbers”, “find all email addresses in the text”, “replace several consecutive question marks with one”.

Let's start with one popular programming wisdom:

Some people, when faced with a problem, think: "Yeah, I'm smart, I'll solve it with regular expressions." Now they have two problems.

Template examples

Let's start with a couple of simple examples. The first expression in the picture below looks for a sequence of 3 letters, where the first letter is "k", the second is any Russian letter, and the third is "t" in a case insensitive way (e.g. "cat" or "CAT" fits this pattern). The second expression searches the text for a time in the format 12:34 .

Any expression begins with a delimiter character (delimiter in English). The symbol / is usually used as it, but other characters that do not have a special purpose in regular expressions, such as ~ , # or @ , can be used. Alternative delimiters are used if the / character can occur in the expression. Then comes the template of the string we are looking for, followed by the second delimiter, and one or more flag letters can go at the end. They set additional options when searching for text. Here are examples of flags:

  • i - says that the search should be case-insensitive (case-sensitive by default)
  • u - says that the expression and the text being searched for use utf-8 encoding, not just latin letters. Without it, the search for Russian (and any other non-Latin) characters may not work correctly, so you should always put it on.

The template itself consists of regular characters and special designs. Well, for example, the letter "k" in regular expressions means itself, but the symbols mean "any number from 0 to 5 can be in this place." Here is a complete list of special characters (in the php manual they are called metacharacters), and all other characters in the regular expression are ordinary:

Below we will analyze the meaning of each of these characters (and also explain why the letter “ё” is placed separately in the first expression), but for now we will try to apply our regular expressions to the text and see what happens. PHP has a special function preg_match($regexp, $text, $match) , which takes a regular expression, text, and an empty array as input. It checks if the text contains a substring that matches the given pattern and returns 0 if not, or 1 if it does. And in the passed array, the first found match with the regular expression is placed in the element with index 0. Let's write a simple program that applies regular expressions to different strings:

Now that we've seen the example, let's explore regular expressions in more detail.

Parentheses in regular expressions

Let's recap what the different types of brackets mean:

  • Curly braces a(1,5) specify the number of repetitions of the previous character - in this example, the expression looks for 1 to 5 consecutive letters "a"
  • Square brackets mean "any one of these characters", in this case, the letters a, b, c, x, y, z, or a number from 0 to 5. Inside square brackets, other special characters like | or * - they denote a regular character. If there is a symbol ^ in square brackets at the beginning, then the meaning is reversed: “any one character, except for those indicated” - for example, [^a-c] means “any one character, except a, b or c”.
  • Parentheses group characters and expressions. For example, in the expression abc+, the plus sign refers only to the letter c, and this expression looks for words like abc, abcc, abccc. And if you put brackets a (bc) + then the plus quantifier already refers to the sequence bc and the expression looks for the words abc, abcbc, abcbcbc

Note: character ranges can be specified in square brackets, but remember that the Russian letter ё is separate from the alphabet and to write "any Russian letter", you must write [а-яё] .

bexleshi

If you have looked at other tutorials on regular expressions, you probably noticed that backslash is written differently everywhere. Somewhere they write one backslash: \d , but here in the examples it is repeated 2 times: \\d . Why?

The regular expression language requires you to write the backslash once. However, in single and double quoted strings in PHP, backslash also has a special meaning: a manual about strings. Well, for example, if you write $x = "\$"; then PHP will take it as a special combination and insert only the $ character into the string (and the regex engine won't know about the backslash before it). To insert the sequence \$ into a string, we must double the backslash and write the code as $x = "\\$"; .

For this reason, in some cases (where a sequence of characters has special meaning in PHP) we are required to double the backslash:

  • To write in regular expression \$ , we write in code "\\$"
  • To write \\ in regular expression, we double each backslash and write "\\\\"
  • To write a backslash and a number (\1) in a regular expression, the backslash must be doubled: "\\1"

In other cases, one or two backslashes will give the same result: "\\d" and "\d" will insert a pair of \d characters into the string - in the first case, 2 backslashes is the sequence for inserting a backslash, in the second case there is no special sequence and characters will be inserted as is. You can check what characters will be inserted into the string, and what the regular expression engine will see, using echo: echo "\$"; . Yes, it's hard, but what can you do?

Special constructions in regular expressions

  • \d looks for any single digit, \D - any single character other than a digit
  • \w matches any single letter (any alphabet), digit, or underscore _ . \W matches any character except letter, number, underscore.

Also, there is a convenient condition for pointing to a word boundary: \b . This construction means that on one side of it there should be a character that is a letter/number/underscore (\w), and on the other side - not. Well, for example, we want to find the word "cat" in the text. If we write the regular expression /cat/ui , then it will find the sequence of these letters anywhere - for example, inside the word "beast". This is clearly not what we wanted. If we add a word boundary condition to the regular expression: /\bcat\b/ui , then now only the separate word "cat" will be searched.

Manual

  • Syntax of regular expressions in PHP, detailed description

One of the very powerful and useful features of the PHP language is support for regular expressions. Many programmers, both beginners and quite experienced, are intimidated by the external complexity and intricacies of the regular expression language. But I can assure you, it's worth it. The use of regular expressions greatly facilitates the work of processing texts and loosely structured data.


Regular expressions are expressions written in a special language. Don't be scared, the language is quite easy to understand, you just need experience and practice.


I think you have repeatedly encountered situations when you have a text (for example, in Microsoft Word) and you need to find something important in it. If you know what you are looking for - everything is simple: you called up the search dialog, entered the search word, pressed the button and voila - the text was found.


But what will you do if you know in advance only the type of information you are looking for? For example, you are faced with the task of finding all the email addresses in a document of a couple of hundred sheets. Some will scan the document manually, some will search for a dog (@) and search for it. Agree - both variants are hard labor ungrateful labor.

This is where regular expressions come in. To some extent, regular expressions can be compared with masks or patterns that are superimposed on text: if the text matches the mask, then this is the desired fragment. But before considering the use of regular expressions, we will get acquainted with their syntax.

A regular expression is a text string composed according to certain laws and rules. A string consists of characters and groups of characters, metacharacters, quantifiers, and modifiers.

Symbols in this case are any symbols of any alphabet. And not only readable. You may well insert an unreadable character into the expression, for this you will only need to know its code in hexadecimal form. For example:

// readable characters a E // unreadable characters and codes \x41 - the same as the letter "A" \x09 - tab character

A group of characters is several characters written in sequence:

Abcg ACZms

I draw your attention right away - the "space" in regular expressions is also considered as a significant character, so be careful when writing expressions. For example, these character groups are DIFFERENT expressions:

ABCWHERE ABC WHERE

The next language element is metacharacters. The prefix "meta" means that these symbols describe some other symbols or their groups. The table discusses the main metacharacters of the regular expression language:

Metacharacters for specifying special characters
() Brackets. Define nested expressions.
| Choice Metacharacter
^ Line start metacharacter
$ End-of-line metacharacter
\n Line feed character (hexadecimal code 0x0A)
\r Carriage return character (hexadecimal code 0x0D)
\t Tab character (hexadecimal code 0x09)
\xhh Inserting a character with hexadecimal code 0xhh, for example \x42 will insert the latin letter "B"
Metacharacters for specifying character groups
. Dot. Any character.
\d Digit (0-9)
\D Not a digit (any character except characters 0-9)
\s Blank character (usually space and tab character)
\S A non-empty character (anything but the characters identified by the \s metacharacter)
\w "Dictionary" character (a character that is used in words. Usually all letters, all numbers, and the underscore ("_"))
\W All but the characters defined by the \w metacharacter

Metacharacters from the second half of the table are very easy to remember. "d" - digit (number), "s" - symbol (symbol), "w" - word (word). If the letter is large, then you need to add "NOT" to the description of the group.

Let's take for example the text "On the red jersey the numbers are 1812, and on the green jersey - 2009". Consider examples of the simplest regular expressions:

\d\d\d\d - matches 1812 and 2009 \D - matches all letters, spaces and punctuation \s - matches all spaces in the text.

But after all, the year in our example can be written not with four, but with two digits, words can have other declensions, etc. Subsets of characters that are specified using square brackets can help here:

Means any digit (same as \d) - means even digit - means any character of the Latin alphabet (in any case) or digit.

For example, the expression \d\d\d in the test string will only find 1812, not 2009. This expression should be read as "find all sequences of four digits where the last digit is 0,2,4,6, or 8".

We only need to mention quantifiers and modifiers.

Quantifier is a special construct that determines how many times a character or group of characters must occur. The quantifier is written in curly brackets "()". Two recording formats are possible: exact and range. Accurate format is written like this:

Here X is the number of times the preceding character or group must be repeated. For example the expression

The second form of notation is range. Written as

(X, Y) // or (,Y) // or (X,)

where X is the minimum and Y is the maximum number of repetitions. For example:

read as "from two to four consecutively written digits". If one of the bounds is not specified, then no constraint is assumed. For example:

\w(3,) - three or more letters. \d(,5) - there are no digits at all, or there are, but no more than five.

Quantifiers can be applied to a single character or to a group:

[A-Zaa-Z](1,3)

This construction will select from the text all Russian words of one, two or three letters (for example, "or", "not", "I", "I go", etc.)

In addition to curly braces with, there are three more quantifier metacharacters: "*" (asterisk), "+" (plus), and "?" (question). They are used in cases where the minimum and maximum number of necessary repetitions is not known in advance. For example, when looking up email addresses, you can't tell in advance how many characters will be in the username (before "dog") and how many characters will be in the domain name (after "dog").

The "*" metacharacter is read as "any number from zero or more", i.e. design

defines any number of consecutive letters, including their complete absence.

The "+" character differs from the asterisk only in that it requires at least one character. Those. design

matches any digit sequence where there is one or more digits.

Symbol "?" matches the absence or presence of a single character. Those. design

matches any digit sequence where there is one or two digits.

Here it is worth mentioning such a feature of the antifiers "*" and "+" as greed. The bottom line is that by default these characters correspond to the longest possible sequence of characters. For example, for the string "mom washed the frame" the expression:

will choose "mom soap ra", which is somewhat unexpected, since we were supposed to get "ma". To change this behavior, use the metacharacter "?" (question mark) written immediately after the quantifier. It limits the "appetite" of quantifiers by making them return the first match, not the longest one. Now let's change the previous example:

and get the desired match "ma".

The last element of the language is modifiers. A modifier is a special character that defines "system" parameters for parsing regular expressions. There are only four such symbols, they can be used both separately and simultaneously:

i Enables case-insensitive mode, i.e. capital and small letters in the expression do not differ.
m Indicates that the text being searched should be treated as multiple lines. By default, the regular expression engine treats text as a single line, regardless of what it actually is. Accordingly, the metacharacters "^" and "$" indicate the beginning and end of the entire text. If this modifier is specified, then they will point to the beginning and end of each line of text, respectively.
s The default metacharacter is "." does not include the newline character in its definition. Those. for multiline text, the expression /.+/ will only return the first line, not the entire text as expected. Specifying this modifier removes this limitation.
U Makes all quantitative metacharacters "non-greedy" by default. In some modifications of the language (particularly in PHP), the character "g" is used instead of "U", more appropriate to the meaning ("g" is short for the English "greedy", "greedy").

The table shows the most popular and necessary examples of regular expressions. Some of them may seem complicated and cumbersome to you, but with a detailed study, you will no doubt figure it out.

Regular Expressions in PHP.

To work with regular expressions in PHP, special functions are intended, the list of which and a brief description are given in the table:

int preg_match(string pattern, string subject[, array matches])

The function checks if the content of subject matches pattern. Returns 1 if matches are found, otherwise returns 0. If you specify the optional array parameter matches, then when the function is executed, only one element will be entered into it - the first match found.

"; print_r($found); ?>

int preg_match_all(string pattern, string subject, array matches[, int order])
The function is identical to the previous one, with the only difference - it searches through the entire text and returns ALL found matches in the matches array.
mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])
Like the two preceding functions, preg_replace searches for a piece of text that matches the pattern. The function replaces all found fragments with the text specified in the parameters.Before cleaning:\n$text\n\n"; $text = preg_replace("/(\n \s(2,))/"," ",$text); echo " After cleaning:\n$text"; // print text stripped of special characters // and extra spaces?>
mixed preg_replace_callback (mixed pattern, mixed callback, mixed subject [, int limit])
The function is an extended version of the previous one. The main difference is that in the parameters this function is passed the name of the function that will analyze the text and form the replacement text.
array preg_split(string pattern, string subject[, int limit[, int flags]])
This function is similar to the explode() and split() functions. Its peculiarity is that the separator is not a fixed string, but a regular expression. The function splits the input data into elements and puts them into the output array.
preg_grep(string pattern, array input)
The function is intended for regular search in arrays. The search is given a pattern and an array of input data, and an array is returned that consists only of elements that match the pattern.

The list of functions considered is far from complete, but it is quite sufficient for a successful start with regular expressions. If you are interested in this topic, be sure to read additional literature (for example, Friedl's book "Regular Expressions"). In addition, for learning purposes, I recommend installing one of the special programs for testing regular expressions (for example, "PCRE" or "RegEx Builder").


2023
maccase.ru - Android. Brands. Iron. News