php
  • regex
  • url
  • 2012-02-02 80 views 0 likes 
    0

    我有一个PHP页面,它通过一些HTML链接查找链接,并用指向本地PHP页面的链接替换它们;问题是找到图像链接。我目前使用此代码:在PHP中识别图像链接

    $data = preg_replace('|(<a\s*[^>]*href=[\'"]?)|','\1newjs.php?url=', $data); 
    

    ,类似的

    <a href="http://google.com">Google</a> 
    

    相匹配的东西,将与

    <a href="newjs.php?url=http://google.com">Google</a> 
    

    我希望做与图像文件类似的东西代替它们(JPG, gif,png)并替换如下:

    <a href="http://google.com/hello.png">Image</a> 
    

    有了这个:

    <a href="newjs.php?url=http://google.com/hello.png&image=1">Image</a> 
    

    注意,在新的URL的 '&图像= 1'。我有可能使用PHP来做到这一点,最好是使用正则表达式吗?

    回答

    1

    按通常累及正则表达式和HTML什么:https://stackoverflow.com/a/1732454/118068

    正确的解决方案是使用DOM操作:

    $dom = new DOMDocument(); 
    $dom->loadHTML(...); 
    $xp = new DOMXPath($dom); 
    $anchors = $xp->query('//a'); 
    foreach($anchors as $a) { 
        $href = $a->getAttribute('href'); 
        if (is_image_link($href)) { // 
         $a->setAttribute('href', ... new link here ...); 
        } 
    } 
    
    +0

    谢谢,这个工作! – q3d 2012-02-02 19:35:25

    相关问题