SoFunction
Updated on 2025-03-02

Regular expressions commonly used in WEB development (PHP and Javascript)

In WEB development, regular expressions are usually used to detect and find and replace certain strings that comply with rules, such as detecting whether the user inputs E-mai format is correct, collecting page content that complies with rules, etc.
Below we use PHP and Javascript to introduce to you the most commonly used and practical regular expressions and their usage in WEB development.

Common PHP expression usage
1. Match positive integer: /^[1-9]\d*$/
2. Match non-negative integers (positive integer + 0): /^\d+$/
3. Match Chinese: /^[\x{4e00}-\x{9fa5}]+$/u
4. Match email: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
5. Match URL: (((f|ht){1}(tp|tps)://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)
6. Match the beginning of the letter, 5-16 characters, alphanumeric underscore: /^[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 the 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 the ID card of mainland China: /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}(\d|x|X)$/
Examples of PHP regular verification string methods:

$str = "Chinese"; 
$preg = "/^[\x{4e00}-\x{9fa5}]+$/u"; //Match Chineseif(preg_match($preg,$str,$arr)){ 
 $msg = 'The match was successful!  '; 
}else{ 
 $msg = 'Match failed!  '; 
} 
echo $msg; 

Common Javascript expression usage
1. Match positive integer: /^[0-9]*[1-9][0-9]*$/
2. Match non-negative integers (positive integer + 0): /^\d+$/
3. Match Chinese: /^[\u4e00-\u9fa5]/
4. Match email: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
5. Match URL: /^(f|ht){1}(tp|tps):\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?/
6. Match the beginning of the letter, 5-16 characters, alphanumeric underscore: /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
7. Match numbers, letters, underscores, Chinese: /^[\u4e00-\u9fa5A-Za-z0-9_]+$/
8. Match the 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 the ID card of mainland China: /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}(\d|x|X)$/
Examples of Javascript regular verification string methods:

var str = "abc@"; 
var preg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/; //Match Emailif((str)){ 
 var msg = "Match Successfully"; 
}else{ 
 var msg = "Match failed!"; 
} 
alert(msg); 

The editor has compiled 20 common expressions, I hope they will be helpful to everyone's learning.

Regular expressions are a subject, and it is impossible to use an article to explain them. There are many theoretical things on the Internet. Interested students can search and learn more.