php
  • hyperlink
  • relative-path
  • 2012-03-17 102 views 6 likes 
    6

    我請求網站這樣的源代碼:使相對鏈接到絕對者

    <? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741'); 
    echo $txt; ?> 
    

    卜我想,以取代那些絕對的相對鏈接!基本上,

    <img src="/images/legend_15s.png"/> and <img src='/images/legend_15s.png'/> 
    

    應由

    <img src="http://domain.com/images/legend_15s.png"/> 
    

    <img src='http://domain.com/images/legend_15s.png'/> 
    

    分別替換。我怎樣才能做到這一點?

    回答

    7

    這個代碼僅替換鏈接和圖像:

    <? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741'); 
    $txt = str_replace(array('href="', 'src="'), array('href="http://stats.pingdom.com/', 'src="http://stats.pingdom.com/'), $txt); 
    echo $txt; ?> 
    

    我已經測試其工作:)

    修訂

    這裏與正則表達式和工作做得更好:

    <? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741'); 
    $domain = "http://stats.pingdom.com"; 
    $txt = preg_replace("/(href|src)\=\"([^(http)])(\/)?/", "$1=\"$domain$2", $txt); 
    echo $txt; ?> 
    

    完成:d

    9

    這可以使用來達到的以下內容:

    <?php 
    $input = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741'); 
    
    $domain = 'http://stats.pingdom.com/'; 
    $rep['/href="(?!https?:\/\/)(?!data:)(?!#)/'] = 'href="'.$domain; 
    $rep['/src="(?!https?:\/\/)(?!data:)(?!#)/'] = 'src="'.$domain; 
    $rep['/@import[\n+\s+]"\//'] = '@import "'.$domain; 
    $rep['/@import[\n+\s+]"\./'] = '@import "'.$domain; 
    $output = preg_replace(
        array_keys($rep), 
        array_values($rep), 
        $input 
    ); 
    
    echo $output; 
    ?> 
    

    哪樣如下輸出鏈接:

    /東西

    將成爲,

    http://stats.pingdom.com//something

    而且

    ../something

    將成爲,

    http://stats.pingdom.com/../something

    但它不會修改「數據:圖像/ PN G;」或錨標籤。

    我很確定正則表達式可以改進。

    +0

    我喜歡這個!感謝您的寫作。巧妙地將preg_replace參數放入鍵中。我實現了這個功能來完成用戶功能請求,以便在我的插件中設置生成Grav網站靜態副本的絕對鏈接。也就是說,如果任何人發現它的問題,我會嘗試在這裏報告它,以便未來的用戶將有一個更好的副本。 – BarryMode 2017-06-18 06:50:53

    1

    你不需要PHP,你只需要使用HTML5的基礎標籤,並把你的PHP代碼的HTML身上,你只需要做好以下 例子:

    <!doctype html> 
    <html lang="en"> 
    <head> 
        <meta charset="UTF-8"> 
        <title>Document</title> 
        <base href="http://yourdomain.com/"> 
    </head> 
    <body> 
    <? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741'); 
    echo $txt; ?> 
    </body> 
    </html> 
    

    ,並會將所有文件使用絕對網址

    相關問題