search
HomeBackend DevelopmentPHP TutorialLearn regular expressions with examples in PHP

Learn regular expressions by looking at examples
First, let us look at two special characters: '^' and '$'. They are used to match the beginning and end of a string respectively. Here are examples:
First, let us look at Look at two special characters: '^' and '$'. They are used to match the beginning and end of the string respectively. Here are examples:
"^The": Matches the string starting with "The";
" of despair$": matches the string ending with "of despair";
"^abc$": matches the string starting with abc and ending with abc, in fact, only abc matches it;
"notice": matches A string containing notice;
You can see that if you do not use the two characters we mentioned (the last example), that is to say, the pattern (regular expression) can appear anywhere in the string being tested, and you do not use it Lock to the sides.
There are also several characters '*', '+', and '?', which are used to represent the number of times or order that a character can appear. They respectively represent: "zero or more", "one or more", and "zero or one." Here are some examples:
"ab*": Matches a string consisting of a and 0 or more b ("a", "ab", "abbb", etc.);
"ab+": Same as above, but with at least one b ("ab", "abbb", etc.);
"ab?": Matches 0 or one b;
"a?b+$": Matches one Or a string ending with 0 a plus one or more b.
You can also limit the number of characters appearing in curly brackets, for example
"ab{2}": matches an a followed by two b (a No less) ("abb");
"ab{2,}": at least two more b("abb", "abbbb", etc.);
"ab{3,5}": 2-5 b("abbb", "abbbb", or "abbbbb").
You should also note that you must always specify (i.e, "{0,2}", not "{,2}"). Likewise, You must notice that '*', '+', and '?' are the same as the following three range annotations, "{0,}", "{1,}", and "{0,1}" respectively .
Now put a certain number of characters into parentheses, for example:
"a(bc)*": matches a followed by 0 or one "bc";
"a(bc){1,5}": one to 5 "bc."
There is also one character '│', which is equivalent to the OR operation:
"hi│hello": matches strings containing "hi" or "hello";
"(b│cd)ef" : Matches strings containing "bef" or "cdef";
"(a│b)*c": Matches strings containing - multiple (including 0) a or b, followed by a c string ;
A dot ('.') can represent all single characters:
"a.[0-9]": an a followed by a character followed by a number (Strings containing such a string will be matched, This bracket will be omitted in the future)
"^.{3}$": ends with three characters. The content enclosed in square brackets only matches a single character
"[ab]": matches a single a or b ( and "a │b" Same);
"[a-d]": Matches a single character from 'a' to 'd' (same effect as "a│b│c│d" and "[abcd]");
"^[ a-zA-Z]": Matches strings starting with letters
"[0-9]%": Matches strings containing x%
",[a-zA-Z0-9]$": Matches A string ending with a comma plus a number or letter
You can also list the characters you don’t want in brackets, you just need to use '^' as the beginning inside the brackets (i.e., "%[^a- zA-Z]%" matches a string containing two percent signs with a non-letter inside).
In order to be able to explain, but when "^.[$()│*+?{" is used as a character with special meaning , you must add '' in front of these characters, and in php3 you should avoid using it at the beginning of the pattern. For example, the regular expression "($│?[0-9]+" should be called ereg( "($│?[0-9]+", $str) (I don’t know if it is the same in php4)
Don’t forget that the characters inside the square brackets are exceptions to this rule - inside the square brackets, all special characters, Including (''), will lose their special properties (i.e., "[*+?{}.]" matches strings containing these characters). Also, as the regx manual tells us: "If the list contains ']', it is best to put it as the first character in the list (maybe after '^'). If it contains '-', it is best to put it at the front or last, or or the first character of a range Two ending points (i.e. [a-d-0-9] with a '-' in the middle will be valid.
For completeness, I should cover collating sequences, character classes, and equivalence classes. But I don't want to go into too much detail on these aspects. , none of this needs to be covered in the following article. You can get more information in the regex man pages.
How to build a pattern to match the currency amount input
Okay, now we are going to use what we have learned. Something useful: Construct a matching pattern to check whether the input information is a number representing money.We think there are four ways to represent the amount of money: "10000.00" and "10,000.00", or without a decimal part, "10000" and "10,000". Now let's start building this matching pattern:
^[1-9][ 0-9]*$
This means that all variables must start with a non-0 number. But this also means that a single "0" cannot pass the test. The following is the solution:
^(0│[1-9] [0-9]*)$
"Only 0 and numbers not starting with 0 match", we can also allow a negative sign before the number:
^(0│-?[1-9][0- 9]*)$
This is: "0 or a number starting with 0 that may have a negative sign in front of it." Okay, okay now let's not be so strict and allow starting with 0. Now let's drop the negative sign , because we don’t need to use it when representing coins. We now specify the pattern to match the decimal part:
^[0-9]+(.[0-9]+)?$
This implies the matching string It must start with at least one Arabic numeral. But note that in the above pattern "10." is not matched, only "10" and "10.2" are acceptable. (Do you know why)
^[0-9]+( .[0-9]{2})?$
We specified above that there must be two decimal places after the decimal point. If you think this is too harsh, you can change it to:
^[0-9]+(.[0-9 ]{1,2})?$
This will allow one or two characters after the decimal point. Now we add commas (every third digit) to increase readability, we can express it like this:
^[0- 9]{1,3}(,[0-9]{3})*(.[0-9]{1,2})?$
Don’t forget that the plus sign '+' can be replaced by the multiplication sign '*' If you want to allow blank strings to be entered (why?). Also don't forget that the backslash '' can cause errors in PHP strings (a very common mistake). Now that we can validate the string, we Now remove all the commas str_replace(",", "", $money) and then treat the type as double and we can do mathematical calculations with it.
Construct a regular expression to check email
Let's continue to discuss how Verify an email address. There are three parts in a complete email address: POP3 username (everything to the left of '@'), '@', server name (that's the rest). Usernames can contain uppercase and lowercase letters Arabic numerals, periods ('.'), minus signs ('-'), and underscores ('_'). The server name also conforms to this rule, except of course the underscore.
Now, the beginning and end of the user name cannot be a period . The same goes for the server. And you can't have two consecutive periods with at least one character between them. Now let's look at how to write a matching pattern for the username:
^[_a-zA-Z0-9-] +$
The existence of periods is not allowed yet. We add it:
^[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*$
The meaning of the above That is to say: "Start with at least one canonical character (except . unexpected), followed by 0 or more strings starting with a dot."
To simplify it a bit, we can use eregi() instead of ereg().eregi() Being case-insensitive, we don’t need to specify two ranges "a-z" and "A-Z" – we only need to specify one:
^[_a-z0-9-]+(.[_a-z0-9- ]+)*$ The server name after
is the same, but the underscore must be removed:
^[a-z0-9-]+(.[a-z0-9-]+)*$
Done. Now just use "@" connects the two parts:
^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9 -]+)*$
This is the complete email authentication matching mode, just call
eregi('^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a -z0-9-]+(.[a-z0-9-]+)*$ ',$eamil)
You can get whether it is email.
Other uses of regular expressions
Extracting strings
ereg() and eregi() have a feature that allows users to extract part of a string through regular expressions (you can read the manual for specific usage). For example, we want to extract from path/URL Extract file name – the following code is what you need:
ereg("([^/]*)$", $pathOrUrl, $regs);
echo $regs[1];
Advanced replacement
ereg_replace () and eregi_replace() are also very useful: if we want to replace all separated negative signs with commas:
ereg_replace("[ ]+", ",", trim($str));

The above has introduced how to learn regular expressions in PHP by looking at examples, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft