PHP/regex:用于创建带短划线而不是空格的文件名的脚本 [英] PHP/regex : Script to create filenames with dashes instead of spaces

查看:77
本文介绍了PHP/regex:用于创建带短划线而不是空格的文件名的脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to amend a PHP script I'm using in wordPress (Auto Featured Image plugin).
The problem is that this script creates filenames for thumbnails based on the URLs of the image.

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

That sounds great until you get a filename with spaces and the thumbnail is something like this%20Thumbnail.jpg and when the browser goes to http://www.whatever.com/this%20Thumbnail.jpg it converts the %20 to a space and there is no filename on the server by that name (with spaces).

要解决此问题,我认为,我需要更改以下行,以便对$ imageURL进行过滤以将%20转换为空格.听起来不错吗?
这是代码.也许您可以告诉我,如果我在树上叫错.
谢谢!

To fix this, I think I need to change the following line in such a way that $imageURL is filtered to convert %20 to spaces. Sound right?
Here is the code. Perhaps you can tell me if I'm barking up the wrong tree.
Thank you!

<?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 );
?>

推荐答案

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

Edited to a more appropriate and complete answer:

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 );

    // ...
}

这篇关于PHP/regex:用于创建带短划线而不是空格的文件名的脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆