简体   繁体   中英

Append to start of href tag

I'm looking to turn
<a href="http://somelink.com/somepage">Some page</a> to
<a href="http://example.com?q=http://somelink.com/somepage">Some page</a>
using PHP. I'll have the HTML code of a random website so it's not as simple as using 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. 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 = 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM