4

Web ページ上のすべての href リンクを見つけて、リンクを独自のプロキシ リンクに置き換えようとしています。

例えば

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

する必要がある

<a href="http://www.example.com/?loadpage=http://www.google.com">Google</a>
4

3 に答える 3

9

PHP を使用DomDocumentしてページを解析する

$doc = new DOMDocument();

// load the string into the DOM (this is your page's HTML), see below for more info
$doc->loadHTML('<a href="http://www.google.com">Google</a>');

//Loop through each <a> tag in the dom and change the href property
foreach($doc->getElementsByTagName('a') as $anchor) {
    $link = $anchor->getAttribute('href');
    $link = 'http://www.example.com/?loadpage='.urlencode($link);
    $anchor->setAttribute('href', $link);
}
echo $doc->saveHTML();

ここで確認してください: http://codepad.org/9enqx3Rv

HTML を文字列として持っていない場合は、 cUrl ( docsloadHTMLFile ) を使用して HTML を取得するか、次のメソッドを使用できます。DomDocument

ドキュメンテーション

于 2012-06-27T22:21:52.087 に答える
0

リンクをjQueryに置き換えたい場合の別のオプションは、次のこともできます。

$(document).find('a').each(function(key, element){
   curValue = element.attr('href');
   element.attr('href', 'http://www.example.com?loadpage='+curValue);

});

ただし、より安全な方法は、php オフコースで行うことです。

于 2012-11-03T16:37:31.187 に答える
-1

これを行うために私が考えることができる最も簡単な方法:

$loader = "http://www.example.com?loadpage=";
$page_contents = str_ireplace(array('href="', "href='"), array('href="'.$loader, "href='".$loader), $page_contents);

しかし、それは ? を含む URL に問題があるかもしれません。また &。または、ドキュメントのテキスト (コードではない) に href=" が含まれている場合

于 2012-06-27T22:23:13.097 に答える