2012-03-24 75 views
0

我想修改我在wordpress(Auto Featured Image插件)中使用的PHP腳本。
問題是,此腳本基於圖像的URL爲縮略圖創建文件名。PHP/regex:使用破折號而不是空格創建文件名的腳本

直到你得到空格的文件名和縮略圖像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); 
?> 
+0

爲什麼不使用md5? – tttony 2012-03-24 06:24:42

+0

其他_字符怎麼樣? – 2012-03-24 06:46:49

+0

@ttony - 使用md5怎麼樣? – user1289585 2012-03-26 08:19:52

回答

1

編輯,以一個更合適,更完整的答案:

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

    // ... 
} 
+0

我錯了,假設問題不在您描述的行中,而是在代碼示例中的第5行?我感謝你的回覆,但我不認爲它回答了我的問題。謝謝! – user1289585 2012-03-26 08:00:59

+0

我認爲你的問題對我來說並不完全清楚:你是想解決一個錯誤還是僅僅修復已保存的縮略圖的文件名中存在%20序列的次要不便之處?據我所知,該腳本從互聯網上的圖像中獲取URL,獲取內容並將該圖像保存到磁盤上以在Wordpress中創建附件。我編輯了代碼以從原始圖像文件名稱中刪除任何轉義字符(如空格,符號等),並用破折號替換這些字符。 – 2012-03-26 09:32:29

+0

$ filename = preg_replace('/%[a-fA-F0-9] {2} /',' - ',$ filename); - 這條線拯救了我的生命!謝謝 – danyo 2014-10-02 19:35:12

0

你最好用下劃線替換圖像名稱的空間或hypens使用正則表達式。

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

這個正則表達式將用一個空格('')替換多個空格(%20)。

+0

codef0rmer - 我不明白你的迴應。我本來不想替換空格。也許我不清楚我的問題。我想要修改上面的腳本,它將文件名作爲以%20替換空格的URL,並使用一個腳本來獲取那些具有%20的文件名,並用破折號替換%20。 – user1289585 2012-03-26 08:00:13

+0

我認爲當你上傳圖片時,它不會替換帶有一些字符的空格(例如下劃線或者超文本),圖片的url有%20個字符替換你不想要的空格。 我的建議是在上傳圖片時用空格替換空格,而不是稍後解析%20。 無論如何,我已經更新了我的答案。 – codef0rmer 2012-03-26 08:07:48

+1

對不起,但我相信那個正則表達式是錯誤的:'/%20 + /'應該是'/(%20)+ /',否則,你只能替換'%20'和'%200','% 2000'等。除此之外,'+'不應該是必須的,並且'g'修飾符是無效的,如果我沒有弄錯,'preg_replace'無論如何都會替換字符串中的所有事件。 – 2012-03-26 09:39:49

相關問題