2012-11-02 204 views
2

我有許多圖像被上傳到一個網站,並有隨機文件名,例如:將字符串插入字符串?

http://www.mysite.com/uploads/images/apicture23.jpg 
http://www.mysite.com/uploads/images/anotherpicture203.jpeg 
http://www.mysite.com/uploads/images/another.picture203.png 
http://www.mysite.com/uploads/images/athird-picture101.gif 

是否有可能在PHP以某種方式文件的擴展名(.jpg.jpeg.png.gif)的URL另一個字符串如-300x200的一部分之前立即插入?

回答

5
$out = preg_replace('/\.[a-z]+$/i','-300x200\0',$in); 

這基本上做到這一點,從左至右:

它取代了什麼開始以點(\.),其次是範圍a-z一個或多個(+)字符,在結束($)的字符串,不區分大小寫(i),由-300x200後跟剛匹配的字符串部分(\0)。

+1

請到OP解釋這樣做,以及如何工作,並在適當的情況下鏈接到文檔。 –

+2

先生,是的,先生! – mvds

+1

我認爲,在'preg_replace'上的谷歌排名前1位將導致官方的php.net文檔。 – mvds

1

如果您希望您上傳的圖片重命名文件名,吼叫課程將幫助您:

<?php 

    function thumbnail($img, $source, $dest, $maxw, $maxh) {  
     $jpg = $source.$img; 

     if($jpg) { 
      list($width, $height ) = getimagesize($jpg); //$type will return the type of the image 
      $source = imagecreatefromjpeg($jpg); 

      if($maxw >= $width && $maxh >= $height) { 
       $ratio = 1; 
      }elseif($width > $height) { 
       $ratio = $maxw/$width; 
      }else { 
       $ratio = $maxh/$height; 
      } 

      $thumb_width = round($width * $ratio); //get the smaller value from cal # floor() 
      $thumb_height = round($height * $ratio); 

      $thumb = imagecreatetruecolor($thumb_width, $thumb_height); 
      imagecopyresampled($thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height); 

      $path = $dest.$img."-300x200.jpg"; 
      imagejpeg($thumb, $path, 75); 
     } 
     imagedestroy($thumb); 
     imagedestroy($source); 
    } 

?> 

 $img   => image file name 
     $source  => the path to the source image 
     $dest  => the path to the destination image 
     $maxw  => the maximum of the image width you desire 
     $maxh  => the minimum one