当前位置:Gxlcms > PHP教程 > php正则表达式示例

php正则表达式示例

时间:2021-07-01 10:21:17 帮助过:15人阅读

正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。

正则表达式是由普通字符(例如字符 a 到 z)以及特殊字符(称为"元字符")组成的文字模式。模式描述在搜索文本时要匹配的一个或多个字符串。正则表达式作为一个模板,将某个字符模式与所搜索的字符串进行匹配。

实例

  1. <?php
  2. $str = <<< EOT
  3. <a href="www/app/a/2QRN7v" rel="external nofollow" >
  4. <p class="phonebg">
  5. <img src="http://www/template9/yunqingjian/jianjie/68.jpg" >
  6. <p class="phoneclick"></p>
  7. <p>幸福领地</p>
  8. </p>
  9. </a>
  10. <a href="www/app/a/uqARNv" rel="external nofollow" >
  11. <p class="phonebg">
  12. <img src="http://www/template9/yunqingjian/jianjie/69.jpg" >
  13. <p class="phoneclick"></p>
  14. <p>一世情长</p>
  15. </p>
  16. </a>
  17. EOT;
  18. if(preg_match_all('%<p.*?>(.*?)</p>%si', $str, $matches)) {
  19. $arr[0][] = $matches[1];
  20. }
  21. if(preg_match_all('/src="([^<]*)" >/i', $str, $matches)) {
  22. $arr[1][] = $matches[1];
  23. }
  24. print_r($arr);
  25. exit;
  26. ?>

运行结果如下:

  1. Array
  2. (
  3. [0] => Array
  4. (
  5. [0] => Array
  6. (
  7. [0] => 幸福领地
  8. [1] => 一世情长
  9. )
  10. )
  11. [1] => Array
  12. (
  13. [0] => Array
  14. (
  15. [0] => http://www/template9/yunqingjian/jianjie/68.jpg
  16. [1] => http://www/template9/yunqingjian/jianjie/69.jpg
  17. )
  18. )
  19. )

以上就是php 正则表达式示例的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行