<a href="http://somelink.com/somepage">Some page</a>
到<a href="http://example.com?q=http://somelink.com/somepage">Some page</a>
str_replace()
那么简单
我已经尝试了Replacing anchor href value with regex,但这似乎只是擦除了整个页面,我得到一个空白的白色屏幕。任何人都可以提供任何帮助吗?
我的代码:
$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
答案 0 :(得分:0)
要使用DOM操作此项,请找到<a>
标记,然后如果有href
属性,请添加前缀。此代码的结尾只是回显了生成的HTML ... < / p>
$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
包含您要添加网址的位。