php
  • regex
  • url
  • 2012-02-02 82 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

    相關問題