regex 如何在PHP中从字符串位置排除图像扩展名

e0uiprwp  于 2023-02-05  发布在  PHP
关注(0)|答案(1)|浏览(99)

我想替换从example.comsample.com的所有字符串值,不包括图像扩展名.png.jpeg.jpg等。

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

我要查找的输出:

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

期望

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
wgeznvg7

wgeznvg71#

你可以用str_replace()加上一点爆炸和内爆来实现。

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

结果

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

相关问题