2017-08-09 49 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