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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。