我有一些 PHP 代码,它可以获取网站的 HTML 代码,然后将其回显到屏幕上。我正在寻找一种扫描 HTML 的方法,然后将所有 href 值替换为另一个值。例如,我有“http://somepage.com" 其中包含 HTML 代码
<a href="http://somepage.com/somepage">Click me</a>
,但是“href”部分的值可能随时更改。我想回显相同的 HTML 代码,但替换href
价值与http://mywebsite.com/somepage
。我怎样才能做到这一点?到目前为止我有这个
$q = htmlentities($_GET['q']);
$html2 = "https://somewebsite.com/search/" . str_replace(' ', '%20', $q);
$html = file_get_contents($html2);
echo $html;
I've seen
PHP DomDocument editing all links, however this returns an error for me
警告:DOMDocument::loadHTMLFile():I/O 警告:加载失败
外部实体
您可以使用预替换()替换字符串中搜索到的术语,如下所示:
<?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;
?>
其输出:
Click me一些示例文本。
Example div
Another link.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)