【问题标题】:preg_match and regex error while parsing string?解析字符串时 preg_match 和正则表达式错误?
【发布时间】:2012-11-25 04:24:58
【问题描述】:

我需要使用 preg_match 删除 url 的一部分,但我从来没有得到我需要的东西。 这里是例子:

$item = "http://example.com/0229883504/?r=2-OR1&p=1";
$item = preg_match_all("/href[^\"]+/i",$item,$matches);
print_r($matches)

我需要返回这个号码

0229883504

我尝试了很多,但是当我 var_dump 匹配数组时,它给出:

Array ( [0] => Array ( [0] => href= ) ) 

我知道问题出在模式之内,但我在这部分做得不太好:)

【问题讨论】:

    标签: php regex string


    【解决方案1】:

    这是您需要的代码:

    $item = "http://example.com/0229883504/?r=2-OR1&p=1";
    $item = preg_match_all("#http://.*?/(.*?)/.*#i",$item,$matches);
    print_r($matches);
    

    如果需要提取值 0229883504,可以添加以下几行:

    $result = $matches[1][0];
    echo $result;
    

    它会像你在这里看到的那样工作:http://ideone.com/H2E9I

    【讨论】:

      【解决方案2】:

      这可以解决上面的例子。

       preg_match_all("/http:\/\/example.com\/([a-zA-Z0-9]+)\//",$item,$matches)
      

      甚至更好:

       preg_match_all("/http:\/\/example.com\/(.+)\//",$item,$matches)
      

      但是,如果您的域可能不同,请使用 Aurelio 的代码示例 :)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-26
        • 2021-07-18
        • 2016-04-29
        • 2012-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多