search
HomeBackend DevelopmentPHP TutorialCommonly used regular expressions in php

Commonly used regular expressions in php

Jan 30, 2020 pm 10:30 PM
regular expression

Commonly used regular expressions in php

Regular expressions are often used when building websites. Here are some explanations and examples for your reference and modification only:

Matching numbers

"^\d $" //Non-negative integer (positive integer 0)

"^[0-9]*[1-9][0-9] *$"  //Positive integer

"^((-\d )|(0 ))$"  //Non-positive integer (negative integer 0)

"^-[0- 9]*[1-9][0-9]*$" // Negative integer

"^-?\d $" // Integer

"^\d (\. \d )?$" //Non-negative floating point number (positive floating point number 0)

"^(([0-9] \.[0-9]*[1-9][0-9 ]*)|([0-9]*[1-9][0-9]*\.[0-9] )|([0-9]*[1-9][0-9]*) )$" //Positive floating point number

"^((-\d (\.\d )?)|(0 (\.0 )?))$" //Non-positive floating point number (negative Floating point number 0)

"^(-(([0-9] \.[0-9]*[1-9][0-9]*)|([0-9]*[ 1-9][0-9]*\.[0-9] )|([0-9]*[1-9][0-9]*)))$" //Negative floating point number

"^(-?\d )(\.\d )?$" //Floating point number

Match letters

"^[A-Za-z] $" / /A string consisting of 26 English letters

"^[A-Z] $" //A string consisting of 26 English letters in uppercase letters

"^[a-z] $" / /A string consisting of 26 lowercase English letters

"^[A-Za-z0-9] $" //A string consisting of numbers and 26 English letters

"^\w $" //A string consisting of numbers, 26 English letters or underscores

Matching example

"^[\w-] (\.[\w-] )*@[\w-] (\.[\w-] ) $"   //email address

"^[a-zA-z] ://(\w (-\w )* )(\.(\w (-\w )*))*(\?\S*)?$" //url

/^(d{2}|d{4} )-((0([1-9]{1}))|(1[1|2]))-(([0-2]([1-9]{1}))|(3[0 |1]))$/ // year-month-day

/^((0([1-9]{1}))|(1[1 |2]))/(([0-2]([1-9]{1}))|(3[0|1]))/(d{2}|d{4})$/ // Month/Day/Year

"^([w-.] )@(([[0-9]{1,3}.[0-9]{ 1,3}.[0-9]{1,3}.)|(([w-] .) ))([a-zA-Z]{2,4}|[0-9]{1, 3})(]?)$" //Emil

/^((\ ?[0-9]{2,4}\-[0-9] {3,4}\-)|([0-9]{3,4}\-))?([0-9]{7,8})(\-[0-9] )?$/ / /Phone number

"^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1 ,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d {1,2}|1dd|2[0-4]d|25[0-5])$" //IP address

Other matching

Regular expression to match Chinese characters: [\u4e00-\u9fa5]

## Matches double-byte characters (including Chinese characters in (within): [^\x00-\xff]

Regular expression matching empty lines:\n[\s| ]*\r

Regular expression matching HTML tags: /.*|/

Regular expression matching leading and trailing spaces: (^\s*)|(\s*$)

Matches Email Regular expression for address: \w ([- .]\w )*@\w ([-.]\w )*\.\w ([-.]\w )*

Regular expression matching URL: ^[a-zA-z] ://(\\w (-\\w )*)(\\.(\\w (-\\ w )*))*(\\?\\S*)?$

Is the matching account legal (starting with a letter, 5-16 bytes allowed, alphanumeric allowed Underline): ^[a-zA-Z][a-zA-Z0-9_]{4,15}$

Matching domestic phone numbers: (\d{3}- |\d{4}-)?(\d{8}|\d{7})?

Matches Tencent QQ number: ^[1-9]*[1-9][0-9 ]*$

metacharacters and their behavior in the context of regular expressions:

\ Marks the next character as a special character, or a literal character, or a backreference , or an octal escape character.

^ Matches the beginning of the input string. If the Multiline property of a RegExp object is set, ^ also matches the position after ’\n’ or ’\r’.

$ Matches the end of the input string. If the Multiline property of the RegExp object is set, $ also matches the position before '\n' or '\r'.

* Matches the preceding subexpression zero or more times

Matches the preceding subexpression one or more times. Equivalent to {1,}.

? Matches the preceding subexpression zero or one time. ? Equivalent to {0,1}.

{n} n is a non-negative integer that matches a certain number of n times.

{n,} n is a non-negative integer, matched at least n times.

{n,m} m and n are both non-negative integers, where n ? When this character immediately follows any of the other qualifiers (*, , ?, {n}, {n,}, {n,m}), the matching pattern is non-greedy. Non-greedy mode matches as little of the searched string as possible, while the default greedy mode matches as much of the searched string as possible.

. Matches any single character except "\n". To match any character including ‘\n’, use a pattern like ‘[.\n]’.

 (pattern) Match pattern and get this match.

(?:pattern) matches pattern but does not obtain the matching result, which means that this is a non-acquisition match and is not stored for later use.

(?=pattern) Forward lookup, match the search string at the beginning of any string matching pattern. This is a non-fetch match, that is, the match does not need to be fetched for later use.

(?!pattern) Negative lookup, opposite to (?=pattern)

x|y matches x or y.

[xyz] character set.

[^xyz] Negative character set.

[a-z] Character range, matches any character within the specified range.

[^a-z] Negative character range, matches any character that is not within the specified range.

\b matches a word boundary, which refers to the position between a word and a space.

\B Matches non-word boundaries.

\cx matches the control character specified by x.

\d matches a numeric character. Equivalent to [0-9].

\D matches a non-numeric character. Equivalent to [^0-9].

\f matches a form feed character. Equivalent to \x0c and \cL.

\n matches a newline character. Equivalent to \x0a and \cJ.

\r matches a carriage return character. Equivalent to \x0d and \cM.

\s matches any whitespace character, including spaces, tabs, form feeds, etc. Equivalent to [ \f\n\r\t\v].

\S matches any non-whitespace character. Equivalent to [^ \f\n\r\t\v].

\t matches a tab character. Equivalent to \x09 and \cI.

\v matches a vertical tab character. Equivalent to \x0b and \cK.

\w Matches any word character including an underscore. Equivalent to '[A-Za-z0-9_]'.

\W matches any non-word character. Equivalent to '[^A-Za-z0-9_]'.

\xn matches n, where n is the hexadecimal escape value. The hexadecimal escape value must be exactly two digits long.

\num matches num, where num is a positive integer. A reference to the match obtained.

\n Identifies an octal escape value or a backreference. If \n is preceded by at least n fetched subexpressions, n is a backreference. Otherwise, if n is an octal number (0-7), then n is an octal escape value.

\nm Identifies an octal escape value or a backreference. If \nm is preceded by at least nm fetched subexpressions, nm is a backreference. If \nm is preceded by at least n gets, then n is a backreference followed by literal m. If neither of the previous conditions is true, then \nm will match the octal escape value nm if n and m are both octal digits (0-7).

\nml If n is an octal digit (0-3), and m and l are both octal digits (0-7), then matches the octal escape value nml.

\un matches n, where n is a Unicode character represented by four hexadecimal digits.

Regular expression matching Chinese characters: [u4e00-u9fa5]

Matching double-byte characters (including Chinese characters): [^x00-xff]

Regular expression matching empty lines: n[s| ]*r

Regular expression matching HTML tags: /. *|/

Regular expression matching leading and trailing spaces: (^s*)|(s*$)

Regular expression matching email addresses: w ([- .]w )*@w ([-.]w )*.w ([-.]w )*

Regular expression matching URL: http://([w-] .) [w-] (/[w- ./?%&=]*)?

Use regular expressions to limit the input content of the text box in the web form:

Use regular expressions to limit only Can input Chinese: onkeyup="value=value.replace(/[^u4E00-u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/ [^u4E00-u9FA5]/g,''))"

Use regular expressions to limit the input of only full-width characters: onkeyup="value=value.replace(/ [^uFF00-uFFFF]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^uFF00-uFFFF]/g,''))"

Use regular expressions to limit input to numbers: onkeyup="value=value.replace(/[^d]/g,'') "onbeforepaste="clipboardData .setData('text',clipboardData.getData('text').replace(/[^d]/g,''))"

Use regular expressions Only numbers and English can be entered: onkeyup="value=value.replace(/[W]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace( /[^d]/g,''))"

Some commonly used regular examples

1. Non-negative integer: ^\d $

2. Positive integer: ^[0-9]*[1-9][0-9]*$

3. Non-positive integer :^((-\d )|(0 ))$

4, negative integer: ^-[0-9]*[1-9][0- 9]*$

5. Integer: ^-?\d $

6. Non-negative floating point number :^\d (\.\d )?$

7, positive floating point number: ^((0-9) \.[0-9]*[1 -9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9] )|([0-9]*[1-9] [0-9]*))$

8. Non-positive floating point number: ^((-\d \.\d )?)|(0 (\. 0 )?))$

9. Negative floating point number: ^(-((positive floating point number regular expression)))$

10. English string: ^[A-Za-z] $

##11. English uppercase string: ^[A-Z] $

12. English lowercase string: ^[a-z] $

13. English character string: ^[A-Za -z0-9] $

14. Alphanumeric and underlined string: ^\w $

##15. E-mail address: ^[\w-] (\.[\w-] )*@[\w-] (\.[\w-] ) $


16. URL: ^[a-zA-Z] ://(\w (-\w )*)(\.(\w (-\w )*))*(\?\s*)? $


Or: ^http:\/\/[A-Za-z0-9] \.[A-Za-z0-9] [\/=\ ?%\-&_~`@[\]\': !]*([^\"\"])*$


##17, Post Coding: ^[1-9]\d{5}$


18, Chinese: ^[\u0391-\uFFE5] $


19. Phone number: ^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3} \)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$


20. Mobile phone number: ^((\(\d{2,3}\))|(\d{3}\-))?13\d{9}$


21. Double-byte characters (including Chinese characters): ^\x00-\xff


22. Match leading and trailing spaces: (^ \s*)|(\s*$) (trim function like vbscript)


23. Match HTML tags: .* |

##24. Match empty lines: \n[\s| ]*\r

25. Extract network links in the information: (h|H)(r|R)(e|E)(f|F) *= *('|" )?(\w|\\|\/|\.) ('|"| *|>)?

26. Extract the email address in the information: \w ([- .]\w )*@\w ([-.]\w )*\.\w ([-.]\w )*

27. Extract the image link in the information: (s|S)(r|R)(c|C) *= *('|")?(\w|\\|\/|\.) ('| "| *|>)?

28. Extract the IP address in the information: (\d )\.(\d )\.(\d )\. (\d )

29. Extract the Chinese mobile phone number in the information: (86)*0*13\d{9}

30. Extract the Chinese landline phone number in the information: (\(\d{3,4}\)|\d{3,4}-|\s)?\d{8}

31. Extract the Chinese phone number in the information (including mobile and landline): (\(\d{3,4}\)|\d{3,4} -|\s)?\d{7,14}

32. Extract the Chinese postal code in the information: [1-9]{1}(\d ) {5}

33. Extract floating point numbers (i.e. decimals) in the information: (-?\d*)\.?\d

34. Extract any number in the information: (-?\d*)(\.\d )?

35. IP: (\d )\.(\d )\.(\d )\.(\d )

36, telephone area code: /^0\d{2, 3}$/

37, Tencent QQ number: ^[1-9]*[1-9][0-9]*$

38. Account number (starting with a letter, allowing 5-16 bytes, allowing alphanumeric underscores): ^[a-zA-Z][a-zA-Z0-9_]{4,15 }$

##39, Chinese, English, numbers and underline: ^[\u4e00-\u9fa5_a-zA-Z0-9] $

Append

Regular expression matching Chinese characters: [\u4e00-\u9fa5]

Matches double-byte characters (including Chinese characters): [^\x00-\xff]

Regular expression that matches blank lines:\n[\ s| ]*\r

Regular expression matching HTML tags: /.*| /

Regular expression matching leading and trailing spaces: (^\s*)|(\s*$)

Regular expression matching IP address: /(\ d )\.(\d )\.(\d )\.(\d )/g //

Regular expression matching email address:\w ( [- .]\w )*@\w ([-.]\w )*\.\w ([-.]\w )*

Match URL Regular expression for URL: http://(/[\w-] \.) [\w-] (/[\w- ./?%&=]*)?

sql statement: ^(select|drop|delete|create|update|insert).*$

The above is the detailed content of Commonly used regular expressions in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:www.liqingbo.cn. If there is any infringement, please contact admin@php.cn delete
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)