Examples of common regular expressions in PHP

The following are some examples of regular expressions commonly used in the PHP language:

1. Verify email address:


$email = '[email protected]';
if (preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', $email)) {
    echo '有效的电子邮件地址';
} else {
    echo '无效的电子邮件地址';
}

2. Verify the URL address:

```php
$url = 'http://www.example.com';
if (preg_match('/^(https?|ftp):\/\/[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:[0-9]+)?\/?([a-zA-Z0-9_\-\.\/%&=\?\#\s]*)?$/', $url)) {
    echo '有效的URL地址';
} else {
    echo '无效的URL地址';
}
```

3. Extract HTML tag content:

```php
$html = '<h1>Welcome to PHP</h1>';
if (preg_match('/<h1>(.*?)<\/h1>/', $html, $matches)) {
    echo '提取的内容是:' . $matches[1];
} else {
    echo '没有匹配到HTML标签内容';
}


```

4. Verify date format (YYYY-MM-DD):

```php
$date = '2023-07-25';
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
    echo '有效的日期格式';
} else {
    echo '无效的日期格式';
}
```

These are just some common examples, you can use more complex regular expressions according to your actual needs. In PHP, you can use the `preg_match()` function for regular expression matching.

Guess you like

Origin blog.csdn.net/qq_26429153/article/details/131921750