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条)

报告相同问题?

悬赏问题

  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改