且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更改< a>的href属性. html文档中的标签

更新时间:2023-02-18 12:25:52

file_get_contents 返回包含以下内容的字符串文件的内容.

file_get_contents returns a string containing the file's content.

因此,您可以使用所需的任何字符串操作函数来处理此字符串,就像您所谈论的那样.

So, you can work in this string using whichever string manipulation function you'd want, like the ones you talked about.

使用str_replace这样的事情可能会做到:

Something like this, using str_replace, would probably do :

$content = file_get_contents('http://www.google.com');

$new_content = str_replace('<a href="', '<a href="site.php?url=', $content);

echo $new_content;

但是请注意,只有当该属性是<a标记的第一个时,它才会替换href属性中的URL.

But note it will only replace the URL in the href attribute when that attribute is the first one of the <a tag...

使用正则表达式可能可以为您提供更多帮助;但恐怕也不是完美的.

Using a regex might help you a bit more ; but it probably won't be perfect either, I'm afraid...

如果您正在使用HTML文档,并且想要一个完整"的解决方案,请使用 DOMDocument::loadHTML 并使用DOM操作方法可能是另一种(稍微复杂一些,但可能更强大的)解决方案.

If you are working with an HTML document and want a "full" solution, using DOMDocument::loadHTML and working with DOM manipulation methods might be another (a bit more complex, but probably more powerful) solution.


根据您愿意做什么,对这两个问题给出的答案可能也可以为您提供帮助:


The answers given to those two questions might also be able to help you, depending on what you are willing to do :

  • underlinks also
  • file_get_contents - also get the pictures

编辑:

如果要替换两个字符串,可以将数组传递给str_replace的前两个参数.例如:

If you want to replace two strings, you can pass arrays to the two first parameters of str_replace. For instance :

$new_content = str_replace(
    array('<a href="', 'Pages'), 
    array('<a href="site.php?url=', 'TEST'), 
    $content);

有了这个:

  • '<a href="'将替换为'<a href="site.php?url='
  • 和'Pages'将被替换为'TEST'
  • '<a href="' will be replaced by '<a href="site.php?url='
  • and 'Pages' will get replaced by 'TEST'

然后,引用手册:

如果搜索和替换是数组, 然后str_replace()从 每个数组并使用它们进行搜索 并替换主题.如果更换 具有比search少的值,然后 空字符串用于其余的 替换值.如果搜索是 数组和替换是一个字符串,然后 此替换字符串用于 搜索的所有价值.

If search and replace are arrays, then str_replace() takes a value from each array and uses them to do search and replace on subject . If replace has fewer values than search , then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search .

如果您要替换'<a href="'的所有实例,那么str_replace默认情况下就是这样:-)

If you want to replace all instances of '<a href="', well, it's what str_replace does by default :-)