PHP正则表达式笔记与实例详解(5)
3.正则表达式匹配网页
//正则匹配函数:preg_match preg_match_all $str=<<<yfstr <div id="mainNav" class="clearfix"> <a href="index.php" rel="external nofollow" >首页</a> <a href="category.php?id=3" rel="external nofollow" >GSM手机</a> <a href="category.php?id=4" rel="external nofollow" >双模手机</a> <a href="category.php?id=6" rel="external nofollow" >手机配件</a> <a href="group_buy.php" rel="external nofollow" >团购 商品</a> <a href="activity.php" rel="external nofollow" >优惠活动</a> <a href="snatch.php" rel="external nofollow" >夺宝奇兵</a> <a href="auction.php" rel="external nofollow" >拍卖活动</a> <a href="exchange.php" rel="external nofollow" >积分商城</a> <a href="message.php" rel="external nofollow" >留言板</a> <a href="http://bbs.ecshop.com/" rel="external nofollow" >EC论坛</a> </div> yfstr; echo "<table width='900' border='1'>"; echo "<tr><th>名称</th><th>URL地址</th><th>链接</th></tr>"; //使用正则匹配 preg_match_all("/<a href=\"(.*?)\".*?>(.*?)<\/a>/s",$str,$a); foreach($a[0] as $k=>$v){ echo "<tr>"; echo "<td>{$a[2][$k]}</td>"; echo "<td>{$a[1][$k]}</td>"; echo "<td>{$v}</td>"; echo "</tr>"; } echo "</table>";
注:使用<<<
这个是php定界符
使用格式:
<<<EOF ... EOF;
使用定界符无需给双引号增加转义字符,可以参考如下:
$str="/<div id=\"mainNav\" class=\"clearfix\">/";
4正则的其他函数使用
//正则的其他函数使用: //preg_quote -- 转义正则表达式字符 //preg_split -- 用正则表达式分割字符串 //preg_replace -- 执行正则表达式的搜索和替换 //1.preg_quote -- 转义正则表达式字符 echo preg_quote("(abc){10}","'");//在每个增则表达式语法的字符前增加一个反斜杠 $s = "a{4}"; preg_match("/".preg_quote($s)."/","werta{4}yu",$a); var_dump($a); echo "<br/>"; //2. preg_split -- 用正则表达式分割字符串 $s = "12,34:56;784;35,67:897:65"; $list = preg_split("/[,:;]/",$s); var_dump($list); echo "<hr/>"; //3. preg_replace执行正则表达式的搜索和替换 $s = "12,34:56;784;35,67:897:65"; //要求将上面的:,;都换成空格 echo preg_replace("/[,;:]/"," ",$s); $str = "<ul style='color:red'> <li>aaaaa</li> <li>bbbbb</li> <li>ddddd</li> <li>eeeee</li> </ul>"; //将上面字串中所有li标签中都添加一个b标签。 echo "<hr/>"; echo $str; echo "<hr/>"; //echo preg_replace("/<li>(.*?)<\/li>/","<li><b>\\1</b></li>",$str); //echo preg_replace("/<li>(.*?)<\/li>/","<li><b>\$1</b></li>",$str); echo preg_replace("/<li>(.*?)<\/li>/",'<li><b>$1</b></li>',$str);
内容版权声明:除非注明,否则皆为本站原创文章。