douli1854 2014-06-21 19:31
浏览 37
已采纳

正则表达式匹配PHP

I’m trying to perform a regex match in PHP and I wonder how to do it correctly.

I looked into preg_match and things but it looks very confusing for a newbie like me.

I know that in AHK (AutoHotKey) I can use this command:

regexmatch(var, "<td style=""""><a.*?>(.*?)</", out)

And var is:

<td style=""><a href="/player/33598934">tofind</a></td>

and then variable out1 would be:

tofind

But how can I achieve this in PHP?

  • 写回答

2条回答 默认 最新

  • drmg17928 2014-06-21 19:44
    关注

    The documention states clearly how to use preg_match(), it briefly explains these parameters.

    preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
    

    Only difference is you would need to use different delimiters, and reduce the double quotes in your regex.

    preg_match('~<td style=""><a.*?>(.*?)</~', $str, $match);
    echo $match[1]; //=> "tofind"
    

    Note: Here we use $match[1] to access what was matched in capturing group #1


    It is alot easier and preferred to use a Parser instead when it comes to parsing HTML.

    $dom = new DOMDocument;
    $dom->loadHTML($html); // Load your HTML data
    
    $xpath = new DOMXPath($dom);
    $node  = $xpath->query("//td//a");
    
    echo $node->item(0)->nodeValue;
    

    Working Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探