繁体   English   中英

PHP / regex:创建带有短划线而不是空格的文件名的脚本

[英]PHP/regex : Script to create filenames with dashes instead of spaces

我想修改在wordPress(自动精选图片插件)中使用的PHP脚本。
问题在于该脚本基于图像的URL为缩略图创建文件名。

这听起来很不错,直到您获得一个带有空格的文件名,并且缩略图类似this%20Thumbnail.jpg ,当浏览器转到http://www.whatever.com/this%20Thumbnail.jpg它将%20转换为一个空格并且该名称的服务器上没有文件名(带空格)。

要解决此问题,我我需要更改以下行,以使$ imageURL被过滤以将%20转换为空格。 听起来对吗?
这是代码。 也许您可以告诉我我是否在错树了。
谢谢!

<?php
  static function create_post_attachment_from_url($imageUrl = null)
  {
      if(is_null($imageUrl)) return null;
      // get file name
      $filename = substr($imageUrl, (strrpos($imageUrl, '/'))+1);
      if (!(($uploads = wp_upload_dir(current_time('mysql')) ) && false === $uploads['error'])) {
          return null;
      }
      // Generate unique file name
      $filename = wp_unique_filename( $uploads['path'], $filename );
?>

编辑为更适当和完整的答案:

static function create_post_attachment_from_url($imageUrl = null)
{
    if(is_null($imageUrl)) return null;

    // get the original filename from the URL
    $filename = substr($imageUrl, (strrpos($imageUrl, '/'))+1);

    // this bit is not relevant to the question, but we'll leave it in
    if (!(($uploads = wp_upload_dir(current_time('mysql')) ) && false === $uploads['error'])) {
        return null;
    }

    // Sanitize the filename we extracted from the URL
    // Replace any %-escaped character with a dash
    $filename = preg_replace('/%[a-fA-F0-9]{2}/', '-', $filename);

    // Let Wordpress further modify the filename if it may clash with 
    // an existing one in the same directory
    $filename = wp_unique_filename( $uploads['path'], $filename );

    // ...
}

最好使用regexp将图像名称中的空格替换为下划线或连字符。

$string = "Google%20%20%20Search%20Amit%20Singhal"
preg_replace('/%20+/g', ' ', $string);

此正则表达式将用单个空格('')替换多个空格(%20)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM