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 可选,存储匹配结果的数组
输出结果:
之所以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的用法也类似。
例子:
输出结果:
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 ) )
相关文章推荐
- preg_match_all使用
- preg_match_all使用实例
- win2003下PHP使用preg_match_all导致apache崩溃问题的解决方法
- preg_match_all使用心得分享
- preg_match_all 函数 使用
- preg_match_all使用实例
- preg_match_all正则表达式的基本使用
- preg_match_all使用心得分享
- php中使用preg_match_all匹配文章中的图片
- PHP 正则表达式匹配 preg_match 与 preg_match_all 函数
- token 6.x-1.17 "preg_match_all() expects parameter 2 to be string, array given in token_scan()" 问题解决
- PHP preg_match的简单使用,验证邮箱地址
- 转载:php 小经验: preg_match 与 preg_match_all 函数
- php中preg_match和preg_match_all的区别
- FOR ALL ENTRIES 使用注意事项
- 使用replaceAll时注意
- preg_match_all心得