doujiang7258 2012-12-04 00:13
浏览 4
已采纳

链接的Preg匹配错误

i am trying to get some preg match done .

i have basically come up with this

preg_match_all('<a href="(.*?)">', $page, $result);

but the output of this is

Array
(
    [0] => Array
     (
        [0] => a href="/stuff"
        [1] => a href="/stuffstuffstuff"

         and much more of this.

i want to remove the a href and the slashes and quotes and keep only the content. ive tried a lot but those things keep coming back , any help would be appretiated.

Thanks guys

  • 写回答

1条回答 默认 最新

  • donglinyi4313 2012-12-04 00:47
    关注

    First thing, please do NOT try to parse random html with regex, it is not going to work, it's going to break, sooner or later. Regex is not tool for parsing html, it CanNOT parse it correctly. 3 simple examples:

    <a href='stuff'> (different quotes)
    <!-- <a href="stuff">-->
    <a style='something' href="stuff">
    

    theese are going to break your application. There is infinite amount of other examples, which will not work and are gonna break it! Not even Chuck Norris can parse html with regex correctly, NOONE can!

    But I assume you already know that, and this is just small simple limited amount of known html, which isn't going to be released in public, so lets back to your question:

    preg_match_all expects the regex with delimiting characters and it matches all that stuff you write between them. If you write

    '<a href="(.*?)">' 
    

    as a regex, it treats the '<' at the begining as a delimiting character, thus not matching it. Write slashes (or any other characters) arround it:

    preg_match_all('/<a href="(.*?)">/', $page, $result);
    

    Now, it's going to match like:

    [0] => <a href="/stuff">
    

    But you want only the '/stuff'. $result gives you an array. In $result[0] is all the regex matched, in $result[1] is first () matched, in $result[2] would be second ( ) sub-expression matched, and so on... So, you want to look in $result[1], you should find what you want there.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 设计一个温度闭环控制系统
  • ¥100 关于加载卡的问题有能知道这个要怎么处理吗?
  • ¥100 rtmpose姿态评估
  • ¥15 java 通过反射找路径下的类,打包后就找不到
  • ¥15 通联支付网上收银统一下单接口
  • ¥15 angular有偿编写,
  • ¥15 centos7系统下abinit安装时make出错
  • ¥15 hbuildex运行微信小程序报错
  • ¥15 关于#python#的问题:我知道这个问题对你们来说肯定so easy
  • ¥15 wpf datagrid如何实现多层表头