Logo Wand.Tools

Regular Expression Generator

Intelligently generate and explain regular expressions, supporting various common pattern matching

Complete PHP Regular Expression Tutorial (with Common Examples) [2025 Most Comprehensive Guide]

  # Complete PHP Regular Expression Tutorial (with Common Examples) [2025 Most Comprehensive Guide]
  
  Regular Expressions in PHP are powerful tools for string processing. This tutorial will provide a set of practical PHP regular expression examples, covering common matching needs like email, mobile numbers, URLs, Chinese characters, HTML tags, etc., helping developers quickly get started with using regex in PHP.
  
  ## ✅ Overview of Regular Expression Functions (preg series)
  
  ```php
  preg_match()      // Perform a regex match, return the first match
  preg_match_all()  // Perform a global regex match, return all matches
  preg_replace()    // Perform regex replacement
  preg_split()      // Split a string using a regular expression
  preg_grep()       // Filter an array based on a regex

📌 Common Regular Expressions and PHP Examples

1️⃣ Matching Email Addresses

$email = "[email protected]";
if (preg_match("/^[\w\-\.]+@([\w\-]+\.)+[a-zA-Z]{2,7}$/", $email)) {
    echo "Valid Email";
}

2️⃣ Matching Mobile Numbers (Mainland China)

$mobile = "13812345678";
if (preg_match("/^1[3-9]\d{9}$/", $mobile)) {
    echo "Valid Mobile Number";
}

3️⃣ Matching URL Addresses

$url = "https://www.example.com";
if (preg_match("/^(https?:\/\/)?([\w\-]+\.)+[a-zA-Z]{2,6}(\/\S*)?$/", $url)) {
    echo "Valid URL";
}

4️⃣ Matching IP Addresses (IPv4)

$ip = "192.168.0.1";
if (preg_match("/^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/", $ip)) {
    echo "Valid IP";
}

5️⃣ Extracting Text Content from HTML Tags

$html = "<p>Hello <strong>world</strong></p>";
preg_match_all("/<[^>]+>([^<]+)<\/[^>]+>/", $html, $matches);
print_r($matches[1]);

6️⃣ Matching Chinese Characters

$str = "你好world";
if (preg_match("/[\x{4e00}-\x{9fa5}]/u", $str)) {
    echo "Contains Chinese";
}

7️⃣ Replacing All Numbers with an Empty String

$str = "abc123def456";
$result = preg_replace("/\d+/", "", $str);
echo $result; // Output abcdef

8️⃣ Splitting a String (by Non-Letter Boundary)

$str = "hello123world,php";
$parts = preg_split("/[^a-zA-Z]+/", $str);
print_r($parts);

🧠 Explanation of Regex Modifiers

Modifier Description
i Case-insensitive match
m Multiline mode
s Dotall mode (. matches newline)
u Support UTF-8 characters
x Ignore whitespace in pattern

Usage:

preg_match("/pattern/i", $str); // Case-insensitive match

🔍 PHP Regular Expression Usage Tips

  • Use preg_match_all to get all match results.
  • Use preg_replace for batch string replacement.
  • All regex related to Chinese characters are recommended to add the u modifier.
  • Special characters in regular expressions must be escaped, such as ., *, ?, (, ), +, etc.
  • Use var_dump() to debug regex results.