【问题标题】:Match all text between two HTML tags using a regex in PHP在 PHP 中使用正则表达式匹配两个 HTML 标记之间的所有文本
【发布时间】:2011-05-19 12:58:09
【问题描述】:

我对正则表达式模式有疑问。结果它返回两个数组......这是我的代码:

$code = preg_match_all("/\< style\>(.*?)\<\/style\>/",$code,$matches);
var_dump($matches);

作为我设置的测试:

$code = ">< xxxxx> try blah fooo blah   < /xxxxx> idfidf oh < x>< /x> < style> blah blah blah style1 < /style>< style>blah blah style 2 x< /style>

它返回 2 个数组,我的意思是

$matches = array
    0 => array
        0 => string '< style> blah blah blah style1 < /style>' (length=38)
        1 => string '< style>blah blah style 2 x< /style>' (length=34)
    1 => array
        0 => string ' blah blah blah style1 ' (length=23)
        1 => string 'blah blah style 2 x' (length=19)

我想要的匹配在第二个数组中。我在标签之间放了空格,因为编辑器没有显示 HTML 标签。

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    你试过了吗:

    echo $matches[0];
    echo $matches[1]; // and so on, depend in the number of matches.
    

    【讨论】:

      【解决方案2】:

      以下代码对我有用:

      $code = "<xxxxx> try blah fooo blah </xxxxx> idfidf oh <x></x> <style> blah blah blah style1 </style><style>blah blah style 2 x</style>";
      $code = preg_match_all("~<style>(.*?)</style>~si", $code, $matches);
      var_dump($matches[1]);
      
      • 修饰符 s 用于 DOT_ALL(包括换行符)
      • 修饰符i 用于忽略大小写匹配

      输出

      array(2) {
        [0]=>
        string(23) " blah blah blah style1 "
        [1]=>
        string(19) "blah blah style 2 x"
      }
      

      不过,为了让您知道从正则表达式解析 HTML 并不是一个好主意,您最好使用许多可用于 php 的 HTML 解析器。

      【讨论】:

        【解决方案3】:

        使用 Xpath 怎么样? http://nl.php.net/manual/en/class.domxpath.php

        为我工作(大多数时候,就是;))

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-10-31
          • 2010-09-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-02
          • 1970-01-01
          • 2022-07-29
          相关资源
          最近更新 更多