PHP编程中正则表达式应用实例一

来源:互联网 发布:网络挂机 编辑:程序博客网 时间:2024/05/29 10:40

      正则表达式应用实例,笔者会在随后的博文里面陆续发布其应用实例。

处理Email地址

      在用户发布的内容中,我们需要捕捉其中的email,给其增加mailto的链接。

code:

   1: $str    = "My email is example@gmail.com";
   2: //$newStr    = ereg_replace("([.a-zA-Z0-9]+@[.a-zA-Z0-9]+)",'//1',$str);
   3: //$newStr    = preg_replace('/([.a-zA-Z0-9]+@[.a-zA-Z0-9]+)/','//1',$str);
   4: //$newStr    = preg_replace('/([.a-zA-Z0-9]+@[.a-zA-Z0-9]+)/','$1',$str);
   5: $newStr    = preg_replace('/([.a-zA-Z0-9]+@[.a-zA-Z0-9]+)/','//1',$str);
   6: echo $newStr,'
'
;

      这里用到了子表达式引用,使用//1或者$1(应用于preg)来引用pattern中的第一个子表达式,依次类推。

扑捉img中的src

      有时我们需要抓取img中的src内容。这里使用到避免贪婪模式方法。

code:

   1: $str    = 'images';
   2:  
   3: preg_match('/src="(.*?)"/', $str, $match);
   4:  
   5: print_r($match);
   6:  
   7: //Array ( [0] => src="http://56hd.com/images/logo.gif", [1] => http://56hd.com/images/logo.gif )

      使用.*?中的?来实现非贪婪模式匹配。

过滤HTML文档JS脚本

      过滤危险脚本,在WEB设计中很重要。

Code:

   1: $script    = '
   2: 
   3: 
   4: 
   9: 
  10: 
  11: 
  12: 
  13: 
  14: 
  16: ';
  17:  
  18: $patten    = '@
原创粉丝点击