简体   繁体   中英

How to change <a> tag href using php file_get_contents()

I am using file_get_contents ( http://example.com/books.php?id=55 ). I am using search and replace function but not working.

<?php
$homepage = file_get_contents('http://example.com/category.php?c=55');
echo $homepage;

// Search replace not working
// str_replace("http://localhost/", "http://example.com/", $homepage );

?>

Out-Put**

<a class="touch" href="/textbook/book1.php">Book1</a>   
<a class="touch" href="/textbook/book2.php"> Book2</a>  
<a class="touch" href="/textbook/book3.php">Book3</a>

If i click on url it show http://localhost/textbook/book1.php . But I want http://mysite[dot]com/link.php?id=http://example.com/textbook/book1.php

Try this

<?php 
$homepage = file_get_contents('http://example.com/category.php?c=55');
$homepage = str_replace("textbook/", "http://localhost/xx/link.php?id=http://example.com/textbook/", $homepage );
echo $homepage;
?>

There is no "localhost" in the code you parsed. So replacing "localhost" will do nothing. You just need to find the link using href and add your custom link. Also there might be any text "textbook" in your HTML.

Try this:

<?php
$homepage = file_get_contents('http://example.com/category.php?c=55');

$str=str_replace("href=\"", "href=\"http://newsite.com/link.php?id=http://example.com/", $homepage );

echo $str;

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