[英]Append to start of href tag
我正在寻找转身
<a href="http://somelink.com/somepage">Some page</a>
以
<a href="http://example.com?q=http://somelink.com/somepage">Some page</a>
使用PHP。 我将拥有一个随机网站的HTML代码,因此它不像使用str_replace()
那样简单
我试过用正则表达式替换anchor href值,但这似乎只是擦除了我的整个页面,并且出现了空白的白色屏幕。 谁能提供任何帮助?
我的代码:
$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
要使用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
包含要添加URL的位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.