【问题标题】:Replace href with a different value用不同的值替换 href
【发布时间】:2018-02-04 15:13:44
【问题描述】:

我有一些 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;


我见过PHP DomDocument editing all links,但是这对我来说返回了一个错误

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

【问题讨论】:

  • 我知道str_replace,但由于我不一定知道href 值,所以我需要一些方法来找出href 值并更改它
  • 试过DOMDocument?
  • $html 是链接吗?
  • @Hugh 你试过我的回答了吗?

标签: php html


【解决方案1】:

您可以使用preg_replace() 来替换字符串中的搜索词,如下所示:

<?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一些示例文本。

示例 div Another link

【讨论】:

    猜你喜欢
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    相关资源
    最近更新 更多