[英]Append to start of href tag
I'm looking to turn 我正在寻找转身
<a href="http://somelink.com/somepage">Some page</a>
to <a href="http://somelink.com/somepage">Some page</a>
以
<a href="http://example.com?q=http://somelink.com/somepage">Some page</a>
using PHP. 使用PHP。 I'll have the HTML code of a random website so it's not as simple as using
str_replace()
我将拥有一个随机网站的HTML代码,因此它不像使用
str_replace()
那样简单
I've tried Replacing anchor href value with regex but that seems to just erase my entire page and I get a blank, white screen. 我试过用正则表达式替换anchor href值,但这似乎只是擦除了我的整个页面,并且出现了空白的白色屏幕。 Can anyone offer any help?
谁能提供任何帮助?
My code: 我的代码:
$html = file_get_contents(htmlentities($_GET['q'])); // Takes contents of website entered by user
$arr = array(); // Defines array
$html2 = ""; // Defines variable to write to later
$dom = new DOMDocument();
$dom->loadHTML($html); // Loads the HTML code displayed earlier
$domcss = $dom->getElementsByTagName('link');
foreach($domcss as $links) {
if( strtolower($links->getAttribute('rel')) == "stylesheet" ) {
$x = $links->getAttribute('href');
$html2 .= '<link rel="stylesheet" type="text/css" href="'.htmlentities($_GET['q']) . "/" . $x.'">';
}
} // This replaces all stylesheets from "./style.css", to "http://example.com/style.css"
echo $html2 . $html // Echos the entire webpage, with stylesheet links edited
To manipulate this with DOM, find the <a>
tags and then if there is a href
attribute, add the prefix in. The end of this code just echos out the resultant HTML... 要使用DOM进行操作,请找到
<a>
标记,然后如果有href
属性,请添加前缀。此代码的末尾只是回显生成的HTML ...
$dom = new DOMDocument();
$dom->loadHTML($html); // Loads the HTML code displayed earlier
$aTags = $dom->getElementsByTagName('a');
$prefix = "http://example.com?q=";
foreach($aTags as $links) {
$href = $links->getAttribute('href');
if( !empty($href)) {
$links->setAttribute("href", $prefix.$href);
}
}
echo $dom->saveHTML();
$prefix
contains the bit you want to add the the URL. $prefix
包含要添加URL的位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.