您的位置:首页 > 编程语言 > PHP开发

preg_match、preg_match_all使用注意点

2016-12-19 21:46 489 查看
preg_match() 函数用于进行正则表达式匹配,成功返回 1 ,否则返回 0 。

preg_match() 匹配成功一次后就会停止匹配,如果要实现全部结果的匹配,则需使用 preg_match_all() 函数。

语法:preg_match (pattern , subject, matches)

pattern 正则表达式

subject 需要匹配检索的对象

matches 可选,存储匹配结果的数组

<?php
//
$subject = "mas23jsadl3lsd23";
$pattern ="/[a-z]*([1-9][0-9]*)/u";
$checked = preg_match($pattern, $subject, $matches);
if($checked){
echo $matches[0]."<br/>";
echo $matches[1]."<br/>";
print_r($matches);
}else{
echo "null";
}


输出结果:

mas23
23
Array ( [0] => mas23 [1] => 23 )


之所以matches[1]只输出23,我们就要了解preg_match的match匹配规则了。如果提供了 matches,则其会被搜索的结果所填充。matches[0] 将包含与整个模式匹配的文本,matches[1] 将包含与第一个捕获的括号中的子模式所匹配的文本,以此类推。

所以pattern =”/[a-z]([1-9][0-9])/u”;中括号是([1-9][0-9]*)所以匹配的是数字23。

同理preg_match_all的用法也类似。

例子:

<?php
$str = '<b>example: </b><div align=left>this is a test</div>';
preg_match_all("|<[^>]+>(.*)</[^>]+>|U", $str, $matchs);
print_r($matchs);
?>


输出结果:

Array
(
[0] => Array
(
[0] => <b>example: </b>
[1] => <div align=left>this is a test</div>
)

[1] => Array
(
[0] => example:
[1] => this is a test
)

)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息