PHP Find&替换url和扩展名

时间:2016-07-07 13:06:27

标签: php html

我一直在寻找一个关于如何使用preg_replace或RegEX到

的示例

在HTML中搜索http://www.mydomain.co.uk/page.html或/page.html

并用.app

替换.html

我只想替换属于此网站的网页上的.html

我有一个使用我们网站页面的应用程序。当我从应用程序链接页面时,我将.app删除/更改格式。哪个有效,我只想动态编辑页面上的链接。

干杯

4 个答案:

答案 0 :(得分:0)

对于那些感兴趣的人,我已经破解了。 它在html中搜索链接,然后检查链接是否属于站点。 在链接中找到“.html”替换为“.app” 查找旧链接替换为html中的新链接。

谢谢你们,我指出了我正确的方向

function searchHTML($html){
// if the page is used by the app replace all domain pages .html with .app

        $domain ='mydomain.com';
        $regEX = '/<a[^>]+href=([\'"])(.+?)\1[^>]*>/I';
        preg_match_all($regEX, $html, $match); //check page for links
        for($l=0; $l<=count($match[2]); $l++){ //loop through links found
            $link = $match[2][$l];//url within href
            if ((strpos($link, $domain) !== false) || ($link[0]=="/")) { //check links are domain links(domain name or the first char is /)
                $updateLink = str_replace(".html", ".app", $link);//replace .html ext with .app ext
                $html = str_replace($link, $updateLink, $html); //update html with new links
            }       
        }        

    return $html;
}

答案 1 :(得分:-1)

function changeURL($url) {
    $url = str_replace('html', 'app', $url);
    return $url;
}

echo changeURL('http://www.mydomain.co.uk/page.html');

结果:http://www.mydomain.co.uk/page.app

答案 2 :(得分:-1)

试试这个,适用于PHP 4&gt; = 4.0.5

<?php
    $string = "http://www.mydomain.co.uk/page.html";
    $string = preg_replace_callback("/mydomain.co.uk\/.+?(html)$/", "replace", $string);

    function replace($matches) {
        return str_replace("html", "app", $matches[0]);
    }

    echo $string;

答案 3 :(得分:-2)

<?php

// it's important to use the $ in regex to be sure to replace only the suffix and not a part of the url

function change_url($url, $find, $replace){
    return preg_replace("#\\.".preg_quote($find, "#")."$#uim", ".".$replace, $url);
    }

echo change_url("http://www.mydomain.co.uk/page.html", "html", "app");

//retuns http://www.mydomain.co.uk/page.app

?>