PHP前端开发

如何使用php正则表达式进行字符集匹配?

百变鹏仔 1个月前 (12-15) #PHP
文章标签 字符集

php 正则表达式提供了一系列字符集匹配符,用于匹配特定的字符模式:【1】方括号 []: 匹配指定字符集内的任何字符;【2】1: 匹配指定字符集之外的字符;【3】d: 匹配数字或与 [0-9] 等价;【4】d: 匹配非数字或与 2 等价;【5】w: 匹配字母数字或与 [a-za-z0-9_] 等价;【6】w: 匹配非字母数字或与 3 等价。... ↩0-9 ↩a-za-z0-9_ ↩

PHP 中正则表达式字符集匹配

正则表达式是用于匹配和处理文本的一种强大工具。PHP 提供了一组字符集匹配符,允许您匹配字符串中符合特定模式的字符。

字符集匹配符

立即学习“PHP免费学习笔记(深入)”;

实战案例

1. 匹配数字(d)

$pattern = '/d/';$subject = '12345';$matches = preg_match_all($pattern, $subject, $matches);print_r($matches);

输出:

Array(    [0] => Array        (            [0] => 1            [1] => 2            [2] => 3            [3] => 4            [4] => 5        ))

2. 匹配非数字(D)

$pattern = '/D/';$subject = 'Test123';$matches = preg_match_all($pattern, $subject, $matches);print_r($matches);

输出:

Array(    [0] => Array        (            [0] => T            [1] => e            [2] => s            [3] => t        ))

3. 匹配字母数字(w)

$pattern = '/w/';$subject = 'My_Username123';$matches = preg_match_all($pattern, $subject, $matches);print_r($matches);

输出:

Array(    [0] => Array        (            [0] => M            [1] => y            [2] => _            [3] => U            [4] => s            [5] => e            [6] => r            [7] => n            [8] => a            [9] => m            [10] => e            [11] => 1            [12] => 2            [13] => 3        ))

4. 匹配非字母数字(W)

$pattern = '/W/';$subject = 'My Username!@#$%^&*()';$matches = preg_match_all($pattern, $subject, $matches);print_r($matches);

输出:

Array(    [0] => Array        (            [0] => !            [1] => @            [2] => #            [3] => $            [4] => %            [5] => ^            [6] => &            [7] => *            [8] => (            [9] => )            [10] =>          ))

  1. 0-9 ↩
  2. a-zA-Z0-9_ ↩