Replace strings possible with output of PHP file_get_contents?
I'm using PHP to get content from an external website.
I want to know if it's possible to find and replace strings from the output so I can make all links absolute.
I need to convert "/ and '/ to "$url/
If it's possible to do开发者_JAVA技巧 that, I can figure out how to do the rest. I don't know if it's possible though.
Thanks
For simple string replacement, use str_replace()
, eg
$html = str_replace(array("'/", '"/'), array("'$url/", '"' . $url . '/'), $html);
If you're after a more robust solution, I'd suggest loading the HTML string into a DOMDocument, loop over all the tags with href
starting with /
and change the attribute of each before writing out the HTML.
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$anchors = $xpath->query('//*[starts-with(@href, "/")]');
foreach ($anchors as $anchor) {
$href = $anchor->getAttribute('href');
$anchor->setAttribute('href', $url . $href);
}
$html = $doc->saveHTML();
You'll probably want to do the same for tags with src
attributes.
You could also use preg_replace(), though the DOMDocument parsing is the most robust.
精彩评论