2017-08-09 47 views
-1

我已經使用以下代碼替換HTML頁面上的所有鏈接。使用PHP替換HTML頁面正文中的所有鏈接使用PHP

$output = file_get_contents($turl); 
$newOutput = str_replace('href="http', 'target="_parent" href="hhttp://localhost/e/site.php?turl=http', $output); 
$newOutput = str_replace('href="www.', 'target="_parent" href="http://localhost/e/site.php?turl=www.', $newOutput); 
$newOutput = str_replace('href="/', 'target="_parent" href="http://localhost/e/site.php?turl='.$turl.'/', $newOutput); 

echo $newOutput; 

我想修改這段代碼,只替換正文中的鏈接而不是正文。

+0

我看到你的評論,你需要保持頭部。看看我更新的答案 – Andreas

回答

0

您可以對代碼進行斬首。
查找身體並將頭部從身體分離爲兩個變量。

//$output = file_get_contents($turl); 

$output = "<head> blablabla 

Bla bla 
</head> 
<body> 
Foobar 
</body>"; 

//Decapitation 
$head = substr($output, 0, strpos($output, "<body>")); 
$body = substr($output, strpos($output, "<body>")); 
// Find body tag and parse body and head to each variable 

$newOutput = str_replace('href="http', 'target="_parent" href="hhttp://localhost/e/site.php?turl=http', $body); 
$newOutput = str_replace('href="www.', 'target="_parent" href="http://localhost/e/site.php?turl=www.', $newOutput); 
$newOutput = str_replace('href="/', 'target="_parent" href="http://localhost/e/site.php?turl='.$turl.'/', $newOutput); 

echo $head . $newOutput; 

https://3v4l.org/WYcYP

+0

是的,這正是我想要的 –

0

您可以使用DOMDocument分析和操作源。對於像這樣的任務使用專用解析器而不是使用字符串操作總是一個更好的主意。

// Parse the HTML into a document 
$dom = new \DOMDocument(); 
$dom->loadXML($html); 

// Loop over all links within the `<body>` element 
foreach($dom->getElementsByTagName('body')[0]->getElementsByTagName('a') as $link) { 
    // Save the existing link 
    $oldLink = $link->getAttribute('href'); 

    // Set the new target attribute 
    $link->setAttribute('target', "_parent"); 

    // Prefix the link with the new URL 
    $link->setAttribute('href', "http://localhost/e/site.php?turl=" . urlencode($oldLink)); 
} 

// Output the result 
echo $dom->saveHtml(); 

https://eval.in/843484