【问题标题】:How to extract the 3 values using preg_match_all [closed]如何使用 preg_match_all 提取 3 个值 [关闭]
【发布时间】:2017-07-29 23:26:06
【问题描述】:

如何在此示例中使用preg_match_all()

<div class="b1 b2 A1 C7" style="right: 9px; top:5px;">
    <div class="tr">1</div>
</div>

<div class="b1 b2  A4 C2" style="right: 19px; top:5px;">
    <div class="tr">2</div>
</div>

<div class="b1 b2  A1 C4" style="right: 29px; top:5px;">
    <div class="tr">2</div>
</div>

我想得到这些值

  1. A1 only A之后的数字
  2. C7 only C之后的数字
  3. &lt;div class="tr"&gt;1&lt;/div&gt; only DIV之间的数字

这是我尝试过的

preg_match_all('/A(.+?) C(.+?)| class="tr">(\d+)<\/div><\/div>/s', $str, $m);

但现在工作我不想使用preg_replace() 换行符或空格。

【问题讨论】:

    标签: php regex preg-match-all


    【解决方案1】:

    这适用于您的具体情况:

    preg_match_all('/A(\d+?)|C(\d+?)|\<div class="tr"\>(\d+?)\<\/div\>/s', $str, $m);
    

    那个回报:

    [0] => Array
        (
            [0] => A1
            [1] => C7
            [2] => <div class="tr">1</div>
            [3] => A4
            [4] => C2
            [5] => <div class="tr">2</div>
            [6] => A1
            [7] => C4
            [8] => <div class="tr">2</div>
        )
    
    [1] => Array
        (
            [0] => 1
            [1] => 
            [2] => 
            [3] => 4
            [4] => 
            [5] => 
            [6] => 1
            [7] => 
            [8] => 
        )
    
    [2] => Array
        (
            [0] => 
            [1] => 7
            [2] => 
            [3] => 
            [4] => 2
            [5] => 
            [6] => 
            [7] => 4
            [8] => 
        )
    
    [3] => Array
        (
            [0] => 
            [1] => 
            [2] => 1
            [3] => 
            [4] => 
            [5] => 2
            [6] => 
            [7] => 
            [8] => 2
        )
    

    【讨论】:

    • 欢迎。如果答案对您有用...可以接受答案...在投票箭头下方查看
    【解决方案2】:

    你想要的模式是:

    /A(\d+) C(\d+)[^<]+<div class="tr">(\d+)/
    

    Demo

    这种模式要快得多,因为它不使用任何管道 (|),并且它使用否定字符类快速移动到最终捕获组。

    同样重要的是要注意我的模式不会进行任何不必要的字符转义。 \d 字符在“贪婪”模式下同样安全,因此可以删除 ?s。

    由于模式中没有.s,s 标志在正则表达式模式的末尾没有任何用途——因此我将其删除。

    与 MTK 的 741 步相比,我的模式只需 90 步即可完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多