duankuai6586 2012-03-13 15:46
浏览 63

使用preg_match从div中获取标签元素的列表

I have the following div:

<div class="divClass">Language:
    <a href="http://www.some-site.com/something/something2/">EN</a>
    <a href="http://de.some-site.com/something/something2/">DE</a>
    <a href="http://es.some-site.com/something/something2/">ES</a>
    <a href="http://fr.some-site.com/something/something2/">FR</a>
    <a href="http://it.some-site.com/something/something2/">IT</a>
    <a href="http://nl.some-site.com/something/something2/">NL</a>
    <a href="http://pt.some-site.com/something/something2/">PT</a>
    <a href="http://ru.some-site.com/something/something2/">RU</a>
    <a href="http://gr.some-site.com/something/something2/">GR</a>
    <a href="http://cn.some-site.com/something/something2/">CN</a>
    <a href="http://pl.some-site.com/something/something2/">PL</a>
    <a href="http://se.some-site.com/something/something2/">SE</a>
</div>

And using this regex pattern:

/<div class="divClass"><a href="(.*)">(.*)<\/a><\/div>/i

To use in the following expression:

$out=preg_replace('/<div class="divClass"><a href="(.*)">(.*)<\/a><\/div>/i',replace_link(substr('$1', strpos('$1','com/')+1),'$2'),$out);

My preg_replace returns NULL. Basically I want to get the link from within the A tag and it's value and replace the links and values with what I get from my replace_link function.

Any ideea how to do that?

Thank you!

  • 写回答

2条回答 默认 最新

  • douman6245 2012-03-13 15:53
    关注

    Your regex is not good: it matches only one <a href=...> </a>, and you provide many.

    You have to use something like:

    /<div class="divClass">\(<a href="(.*)">(.*)<\/a>\)+<\/div>/i
    

    (not sure of the non-capturing syntax in php)

    And you must also deal with spaces (space char, tab, end of line) in your input. If you're sure of your input, you can use something like:

    /<div class="divClass">[^<]*(<a href="(.*)">(.*)<\/a>[^<]*)+[^<]*<\/div>/i
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化