如何使用preg_replace更改url链接?

时间:2013-06-10 03:35:30

标签: php

我有一个url src:

$url = 'http://www.test.com/uploads/2013/06/test.jpg';

我的代码:

preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '-220x220', $url);

如何使用preg_replace结果

$url = 'http://www.test.com/uploads/2013/06/test-220x220.jpg';

2 个答案:

答案 0 :(得分:0)

似乎你想让尺寸部分可选:

preg_replace('/(-\d+x\d+)?(?=\.(jpg|jpeg|png|gif)$)/i', '-220x220', $url);

And that seems to work.

答案 1 :(得分:0)

如果目标只是在文件名和扩展名之间插入'-220x220',则可以使用:

$url = 'http://www.test.com/uploads/2013/06/test.jpg';

$file = pathinfo(basename($url));
if (in_array($file['extension'], array('jpg', 'jpeg', 'png', 'gif')) {
    $url = dirname($url) . '/' . $file['filename'] . '-220x220.' .$file['extension'];
}

另请参阅:basename()pathinfo()