Home > Article > Backend Development > Commonly used regular expressions and usage examples in PHP and javascript_PHP tutorial
In computer science, regular expressions are used to describe or match a series of individual strings that conform to a certain syntax rule. In WEB development, regular expressions are usually used to detect, find and replace certain strings that comply with the rules, such as detecting whether the user input email format is correct, collecting page content that meets the rules, etc.
Today we use PHP and Javscript to introduce to you the most commonly used and practical regular expressions and their usage in WEB development. Regular expressions are a subject and it is impossible to explain them all in one article. There are many theoretical things on the Internet. Interested students can search a lot. However, you may not need to immerse yourself in learning regular expressions that are difficult to figure out. This article and examples will show you commonly used and practical regular expressions.
Common expression usage in PHP:
1. Match positive integers: /^[1-9]d*$/
2. Match non-negative integers (positive integers + 0): /^d+$/
3. Match Chinese: /^[x{4e00}-x{9fa5}]+$/u
4. Match Email: /^w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*/
5. Matching URL: (((f|ht){1}(tp|tps)://)[-a-zA-Z0-9@:%_+.~#?&//=]+)
6. Match the beginning of letters, 5-16 characters, alphanumeric and underline: /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
7. Match numbers, letters, underscores, Chinese: /^[x{4e00}-x{9fa5}A-Za-z0-9_]+$/u
8. Match Chinese postal code: /^[1-9]d{5}$/
9. Match IP address: /b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?). ){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)b/
10. Match mainland China ID card: /^[1-9]d{5}[1-9]d{3}((0d)|(1[0-2]))(([0|1|2 ]d)|3[0-1])d{3}(d|x|X)$/
Example of PHP regular verification string method:
Javascript common expression usage
1. Match positive integers: /^[0-9]*[1-9][0-9]*$/
2. Match non-negative integers (positive integers + 0): /^d+$/
3. Match Chinese: /^[u4e00-u9fa5]/
4. Match Email: /^w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*/
5. Matching URL: /^(f|ht){1}(tp|tps)://([w-]+.)+[w-]+(/[w- ./?%&=] *)?/
6. Match the beginning of letters, 5-16 characters, alphanumeric and underline: /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
7. Match numbers, letters, underscores, Chinese: /^[u4e00-u9fa5A-Za-z0-9_]+$/
8. Match Chinese postal code: /^[1-9]d{5}$/
9. Match IP address: /b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?). ){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)b/
10. Match mainland China ID card: /^[1-9]d{5}[1-9]d{3}((0d)|(1[0-2]))(([0|1|2 ]d)|3[0-1])d{3}(d|x|X)$/
Example of Javascript regular verification string method: