PHP中preg_match_all函数正则匹配详解
preg_match_all函数是用来获取指定数据内容的,它经常用于执行正则表达多,下面我来给大家介绍两个关于preg_match_all函数实现,一个是获取url参数,一个是获取内容中图片方法.
preg_match_all — 执行一个全局正则表达式匹配
int preg_match_all ( string $pattern ,string $subject [,array &$matches [, int $flags = PREG_PATTERN_ORDER [,int $offset = 0 ]]] )
例,代码如下:
- <?php
- preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
- "<b>example: </b><div align=left>this is a test</div>",
- $out, PREG_PATTERN_ORDER);
- echo $out[0][0] . ", " . $out[0][1] . "n";
- echo $out[1][0] . ", " . $out[1][1] . "n";
- ?>
如何获取伪静态url中的参数变量,已经对应的值,比如说,你现在url的是这样的,/js/d1b3cid419299191rs好脚本.
你的.htaccess文件会这样写rewirte规则 RewriteRule ^js/(.*)$ /index.php?m=Sell&a=index&g=$1 [QSA,PT,L]
这样你就可以把g接收过来,代码如下:
- $get = 'd1b3cid419299191rs好脚本';
- $rs_pos = strpos($get,'rs');
- if($rs_pos !== false)
- {
- $rs = substr($get,$rs_pos);
- $rs = str_replace('rs','',$rs);
- $rs = strpos($rs,'/')!==false ? substr($rs,0,strpos($rs,'/')) : $rs;
- $get = substr($get,0,$rs_pos);
- }
- echo 'keywords='.$rs;
- echo '<br>';
- preg_match_all('/([a-z]*)([0-9]+)/',$get,$m);
- if($m)
- {
- $k = $v = '';
- $count = count($m[1]);
- for($i = 0; $i <= $count; $i++)
- {
- ${$m[1][$i]} = $m[2][$i];
- if(isset(${$m[1][$i]}))
- {//开源代码phpfensi.com
- echo $m[1][$i].'='.${$m[1][$i]};
- echo '<br>';
- }
- }
- }
- //结果:keywords=好脚本,d=1,b=3,cid=419299191
匹配文章中的图片,代码如下:
- <?php
- $con = file_get_contents("http://www.phpfensi.com/");
- $pattern="/<[img|IMG].*?src=['|"](.*?(?:[.gif|.jpg|.png]))['|"].*?[/]?>/";
- preg_match_all($pattern,$con,$match);
- print_r($match);
- ?>
- 输出代码
- Array
- (
- [0] => Array
- (
- [0] => <img src="http://www.phpfensi.com/usr/themes/dddefault/images/logo.png" alt="" />
- [1] => <img title="" src="http://www.phpfensi.com/usr/uploads/2012/09/531656480.jpg" alt="2" />
- [2] => <img src="http://www.phpfensi.com/usr/uploads/2012/09/2647136297.jpg" alt="875EA1C00E50B4542797E24FA6E7E1F2.jpg" />
- )//开源代码phpfensi.com
- [1] => Array
- (
- [0] => http://www.phpfensi.com/usr/themes/dddefault/images/logo.png
- [1] => http://www.phpfensi.com/usr/uploads/2012/09/531656480.jpg
- [2] => http://www.phpfensi.com/usr/uploads/2012/09/2647136297.jpg
- )
- )