用regex -php操纵img src

时间:2012-02-06 11:11:45

标签: php regex preg-replace

我该如何替换它:

http://example.com/myfolder/files/year/month/imagename-widthxheight.imageextension

到此:

http://example.com/myfolder/files/year/month/imagename-300x300.imageextension

任何帮助?

2 个答案:

答案 0 :(得分:1)

您可能想尝试这个

// if your src has widthxheight are specified literally like that you may try
echo preg_replace("/\W{0,1}(width).*(height)/i","-300x300","http://www.mysite.com/myfolder/files/year/month/imagename-widthxheight.imageextension");
// if your src has widthxheight are specified in int val you may try     
echo preg_replace("/\W{0,1}(\d{1,7}).*(\d{1,7})/i","-300x300","http://www.mysite.com/myfolder/files/year/month/imagename-123x456.imageextension");

-300x300的实际值会因您的实际需求而异。所以我认为最好通过变量传递这些值。

答案 1 :(得分:1)

怎么样:

$new_img = preg_replace("~([^/]+)-widthxheight(\.[^.]+)$~i","$1-300x300$2", 
"http://www.mysite.com/myfolder/files/year/month/imagename-widthxheight.imageextension");