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 提供了一组字符集匹配符,允许您匹配字符串中符合特定模式的字符。
字符集匹配符
- []: 匹配方括号内指定的字符集中的任何一个字符。
- [^...]: 匹配方括号内指定的字符集之外的任何字符。
- \d: 匹配任何数字。等同于 [0-9]。
- \D: 匹配任何非数字。等同于 1。
- \w: 匹配任何字母数字字符。等同于 [a-zA-Z0-9_]。
- \W: 匹配任何非字母数字字符。等同于 2。
实战案例
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] =>
)
)
- 0-9 ↩
- a-zA-Z0-9_ ↩
以上就是如何使用php正则表达式进行字符集匹配?的详细内容,更多请关注知识资源分享宝库其它相关文章!







发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。