用不同的值替换 href [英] Replace href with a different value

查看:23
本文介绍了用不同的值替换 href的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 PHP 代码可以抓取网站的 HTML 代码,然后将其显示到屏幕上.我正在寻找一种扫描 HTML 的方法,然后将所有 href 值替换为另一个值.例如,我有http://somepage.com",其中包含 HTML 代码
<a href="http://somepage.com/somepage">点击我</a>,但是href"部分的值可以随时更改.我想回显相同的 HTML 代码,但将 href 值替换为 http://mywebsite.com/somepage.我怎样才能做到这一点?到目前为止我有这个

I have some PHP code which grabs a website's HTML code, then echos it to the screen. I'm looking for a way to scan the HTML, and then replace all href values with another value. For example, I have "http://somepage.com" which contains the HTML code
<a href="http://somepage.com/somepage">Click me</a>, however the value of the "href" part could change at any time. I want to echo the same HTML code, but replace the href value with http://mywebsite.com/somepage. How can I do that? I have this so far

$q = htmlentities($_GET['q']);

$html2 = "https://somewebsite.com/search/" . str_replace(' ', '%20', $q);

$html = file_get_contents($html2);

echo $html;

<小时>我已经看到 PHP DomDocument 编辑所有链接,但是这对我来说返回一个错误


I've seen PHP DomDocument editing all links, however this returns an error for me

警告:DOMDocument::loadHTMLFile():I/O 警告:加载失败外部实体

Warning: DOMDocument::loadHTMLFile(): I/O warning : failed to load external entity

推荐答案

您可以使用 preg_replace() 像这样替换字符串中的搜索词:

You can use preg_replace() to replace the searched term in the string like this:

<?php
// example page contents
$pageContents = '<a href="http://somepage.com/somepage">Click me</a>Some example text.
<div>Example div <a href="http://anotherDomain.com/somepage2">Another link</a>.</div>';

//  ------ the Search pattern explanation -------
// (http:\/\/)? means that the http:// may or may not exist
// ([\w]+) the parentheses () will remember the expression inside
// the \s? means there may or may not be a space character there

//  ------ the Replace pattern explanation -------
// replace the matched expression with the provided replacement
// the $2 is the second parenthesized expression () from the search pattern
$html = preg_replace('/<a href="(http:\/\/)?[\w.]+\/([\w]+)"\s?>/', '<a href="http://mywebsite.com/$2">' ,$pageContents);

echo $html;
?>

输出:

点击我一些示例文本.

这篇关于用不同的值替换 href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆