Home > Blockchain >  How to exclude image extension from string place in PHP
How to exclude image extension from string place in PHP

Time:02-03

I want to replace all the string values from example.com to sample.com excluding the image extension .png, .jpeg, .jpg etc.

$body = ' www.example.com, example.com, example.com/hello.html, example.com/logo.png, example.com/yourbaby.php , example.com/newimage.jpg, www.example.com/newimage.jpg';

//values    
$oldomain = ['example.com','www.']; 
$newdomain= ['sample.com', ''];
$excludeextension = [".png", ".jpg", ".jpeg"];

//Replace    
$body = str_replace($olddomain, $newdomain, $body);
$body = str_replace($excludeextension, '', $body);

//output    
 echo $body; 

Output i am looking for :

sample.com, sample.com, sample.com/hello.html, example.com/logo.png, sample.com/yourbaby.php , example.com/newimage.jpg, www.example.com/newimage.jpg

Expectation

https://example.com -> https://sample.com

https://www.example.com -> https://sample.com

https://subdomain.example.com -> https://subdomain.sample.com

https://www.example.com/image.png -> https://www.example.com/image.png

https://example.com/image.png -> https://example.com/image.png

CodePudding user response:

You can do this using str_replace() and a bit of exploding and imploding.

$body = ' www.example.com, example.com, example.com/hello.html, example.com/logo.png, example.com/yourbaby.php, example.com/newimage.jpg, www.example.com/newimage.jpg';

$oldomain = ['example.com','www.']; 
$newdomain= ['sample.com', ''];
$excludeextension = ["png", "jpg", "jpeg"];

$doms = explode(',', $body);
foreach ($doms as &$dom) {
    // get extension
    $pi = pathinfo($dom);
    if ( ! in_array( $pi['extension'], $excludeextension) ){
        $dom = str_replace($oldomain, $newdomain, $dom);
    }

}
$NewStr = implode($doms);
echo $NewStr;

RESULT

sample.com sample.com sample.com/hello.html example.com/logo.png sample.com/yourbaby.php example.com/newimage.jpg www.example.com/newimage.jpg
  • Related