用不同的值替换href

时间:2018-02-04 15:13:44

标签: php html

我有一些PHP代码可以抓取网站的HTML代码,然后将其回显到屏幕上。我正在寻找一种扫描HTML的方法,然后用另一个值替换所有href值。例如,我有“http://somepage.com”,其中包含HTML代码
href,但“href”部分的值可能随时更改。我想回显相同的HTML代码,但将http://mywebsite.com/somepage值替换为$q = htmlentities($_GET['q']); $html2 = "https://somewebsite.com/search/" . str_replace(' ', '%20', $q); $html = file_get_contents($html2); echo $html; 。我怎样才能做到这一点?到目前为止我有这个

$('#button').on('click touchstart', function () {
        $('html, body').animate({
                scrollTop: $("#top-text").offset().top
            }, 1200);

    })

<小时/> 我见过PHP DomDocument editing all links,但这会为我返回错误

  

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

1 个答案:

答案 0 :(得分:0)

您可以使用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