ajl80 ajl80 - 1 year ago 50
PHP Question

PHP Find & Replace where url and extension

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.


Answer Source

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); $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;