PHP/regex : Script to create filenames with dashes

2019-08-24 12:21发布

问题:

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.

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

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

回答1:

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

    // ...
}


回答2:

You better to replace the spaces in image name with underscores or hypens using regexp.

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

This regex will replace multiple spaces (%20) with a single space(' ').