3.4. 字母、数字、下划线
1、匹配包含字母(包含大小写)、数字、下划线的字符
元字符
\w
和[a-zA-z0-9_]
含义相同
<?php
//字符串
$str = '1a_2b_3c';
//正则表达式
$regular = '/\w/';
//执行匹配正则表达式
preg_match_all($regular, $str, $matches);
//打印结果
echo '<pre>';
print_r($matches);
echo '</pre>';
输出结果
Array
(
[0] => Array
(
[0] => 1
[1] => a
[2] => _
[3] => 2
[4] => b
[5] => _
[6] => 3
[7] => c
)
)
2、匹配非字母(包含大小写)、数字、下划线的字符。
元字符
\W
和[^a-zA-z0-9_]
含义相同
<?php
//字符串
$str = '1a_2b_3c';
//正则表达式
$regular = '/\W/';
//执行匹配正则表达式
preg_match_all($regular, $str, $matches);
//打印结果
echo '<pre>';
print_r($matches);
echo '</pre>';
输出结果
Array
(
[0] => Array
(
)
)
推荐文章: