【问题标题】:Preg_match help for finding countPreg_match 帮助查找计数
【发布时间】:2010-06-27 14:51:21
【问题描述】:

大家好 我有一个字符串

<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>

我需要得到 10000 作为答案 .. 我如何使用 preg_match ???注意:这是重要的,匹配的多次出现

提前致谢

【问题讨论】:

    标签: php regex preg-match pcre


    【解决方案1】:

    至少对于这种特殊情况,您可以使用'/\(\d+\-\d+ of (\d+)\)/' 作为pattern

    它匹配像({one-or-more-digits}-{one-or-more-digits} of {one-or-more-digits}) 这样的字符串,并将最后一个{one-or-more-digits} 捕获到一个组中(为了清楚起见,这里添加了{}s..)。

    $str = '<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>';
    $matches = array();
    if (preg_match('/\(\d+\-\d+ of (\d+)\)/', $str, $matches))
    {
        print_r($matches);
    }
    

    打印:

    Array
    (
        [0] => (1-20 of 10000)
        [1] => 10000
    )
    

    因此,您正在寻找的 10000 可以通过 $matches[1] 访问。


    在您的评论后编辑:如果您有多次出现({one-or-more-digits}-{one-or-more-digits} of {one-or-more-digits}),您可以使用preg_match_all 来捕获它们。如果没有它们出现的上下文,我不确定这些数字本身有多大用处,但您可以这样做:

    $str = '<font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>';
    $str .= "\n$str\n";
    echo $str;
    $matches = array();
    preg_match_all('/\(\d+\-\d+ of (\d+)\)/', $str, $matches);
    print_r($matches);
    

    打印:

    <font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>
    <font size="+1"><b>Open Directory Sites</b></font> (1-20 of 10000)<p>
    Array
    (
        [0] => Array
            (
                [0] => (1-20 of 10000)
                [1] => (1-20 of 10000)
            )
    
        [1] => Array
            (
                [0] => 10000
                [1] => 10000
            )
    
    )
    

    同样,您要查找的内容将在 $matches[1] 中,只是这一次它将是一个包含 1 个或多个实际值的数组。

    【讨论】:

    • 没有大括号的(\d+) 有什么作用?
    • 。如果字符串只包含一个(10000 中的 1-20),它可以正常工作......但在我的情况下,有可能多次出现
    • 您介意编辑您的问题以反映真实情况吗?
    • @sAc 我不确定我是否理解你的问题?
    • 非常感谢你我得到了答案:)
    猜你喜欢
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多