将字符串插入字符串?

时间:2012-11-02 01:30:05

标签: php

我有一些图像被上传到具有随机文件名的网站,例如

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)之前立即插入另一个字符串,例如{{} 1}}?

2 个答案:

答案 0 :(得分:5)

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

这基本上是这样做的,从左到右阅读:

它会替换以点(\.)开头的所有内容,后跟+范围内的一个或多个(a-z)字符,最后($)字符串,不区分大小写(i),-300x200后跟匹配的字符串部分(\0)。

答案 1 :(得分: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