如何更改<;a>;使用php file_get_contents()标记href


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

我正在使用file_get_contents(http://example.com/books.php?id=55)。我正在使用搜索和替换功能,但不起作用。

<?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 );
?>

输出**

<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>

如果我点击url,它会显示http://localhost/textbook/book1.php。但是我想要http://mysite[dot]com/link.php?id=http://example.com/textbook/book1.php

试试这个

<?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;
?>

您解析的代码中没有"localhost"。因此,替换"localhost"将毫无作用。您只需要使用href找到链接,然后添加您的自定义链接。此外,HTML中可能有任何文本"教科书"。

试试这个:

<?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;