Sammy Miri Sammy Miri - 4 months ago 21
PHP Question

preg_replace entire string if currently contains a string

i would like to replace the entire URL to completely new one if the URL currently contains an unwanted string.

this is what i tried.

if (preg_match('/(site1.com)/i')){
$url = preg_replace('/(site1.com)/i',('http://www.site2.com/newsite/index.php?a=b'),$url);
}


any help is appreciated.

Answer

It doesn't seem necessary to do a preg_replace if you want to replace the entire string. So, try this:

$url = 'http://www.site1.com/';
$pattern = '/(site1.com)/i';
$newUrl = 'http://www.site2.com/newsite/index.php?a=b';

if (preg_match($pattern, $url)){
    $url = $newUrl;
}

print_r($url);
Comments