dtnat80842 2016-07-07 13:06
浏览 109
已采纳

PHP查找并替换url和扩展名

I've been looking for an example on how to use preg_replace or RegEX to

search HTML for either http://www.mydomain.co.uk/page.html or /page.html

and replace .html with .app

I only want to replace the .html on pages that belong to this site

I have an app that uses pages from our website. When I link page from the app I put .app so it removes/ changes the formatting. Which works, I just want to dynamically edit the links on the pages.

Cheers

  • 写回答

4条回答 默认 最新

  • dongxianchu3541 2016-07-12 10:39
    关注

    OK for those interested, I've cracked it. It searches html for links then checks if the link belongs to site. Find ".html" replace with ".app" within the link Find old links replace with new links within html.

    Thanks guys you pointed me in the right direction

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 关于加载卡的问题有能知道这个要怎么处理吗?
  • ¥100 rtmpose姿态评估
  • ¥15 java 通过反射找路径下的类,打包后就找不到
  • ¥15 通联支付网上收银统一下单接口
  • ¥15 angular有偿编写,
  • ¥15 centos7系统下abinit安装时make出错
  • ¥15 hbuildex运行微信小程序报错
  • ¥15 关于#python#的问题:我知道这个问题对你们来说肯定so easy
  • ¥15 wpf datagrid如何实现多层表头
  • ¥15 为啥画版图在Run DRC会出现Connect Error?可我Calibre的hostname和计算机的hostname已经设置成一样的了。