2017-08-18 121 views
1

我正在使用一個包含此功能的WordPress插件,但插件開發人員並沒有特別快速地做出響應。未定義的偏移量/ PHP錯誤

它應該得到一個YouTube網址的視頻ID,而是我得到一個「未定義的偏移:1」的錯誤。有沒有我錯過的編碼錯誤?

下面是函數:

function youtube_id_from_url($url) { 
    $pattern = 
     '%^# Match any youtube URL 
     (?:https?://)? # Optional scheme. Either http or https 
     (?:www\.)?  # Optional www subdomain 
     (?:    # Group host alternatives 
      youtu\.be/ # Either youtu.be, 
     | youtube\.com # or youtube.com 
      (?:   # Group path alternatives 
      /embed/  # Either /embed/ 
      | /v/   # or /v/ 
      | /watch\?v= # or /watch\?v= 
     )    # End path alternatives. 
     )    # End host alternatives. 
     ([\w-]{10,12}) # Allow 10-12 for 11 char youtube id. 
     $%x' 
     ; 
    $result = preg_match($pattern, $url, $matches); 
    if (false !== $result) { 
     return $matches[1]; 
    } 
    return false; 
} 

我試圖做一個print_r,看看有什麼陣列$matches樣子,它似乎只是一個空數組,所以我想呼應$result和它返回0,這意味着preg_match()沒有找到匹配,對嗎?如果是的話,我可以找出什麼是錯$pattern這將使它返回0

UPDATE: 顯然有這麼走的是URL,使一個鏈接出來的,然後保存一些其他的功能,作爲$url變量。如果我回顯$url變量它打印爲<a href="youtube url">youtube url</a>.

因此,這解釋了錯誤,但我如何修改正則表達式,以適應html標記?如果發生錯誤,

+1

您可以添加導致錯誤的網址是什麼? – FluffyKitten

+2

'preg_match'永遠不會返回boolean'false'(除非有錯誤)。通常它返回一個'1'或'0'。該檢查應該僅僅是'如果($結果){' – Phil

+0

工作對我來說很好(比@Phil說,其他):https://3v4l.org/eTvqp – ishegg

回答

1

的preg_match只會返回FALSE,在這種情況下,你可能想知道是否有匹配或不匹配。所以,你應該能夠切換線路:

if (false !== $result) { 

if (isset($matches[1])) { 

if ($result && isset($matches[1])) { 

菲爾指出的,你真正需要的是:

if($result) { 

菲爾的修改完整修改後的功能fication的正則表達式:

function youtube_id_from_url($url) { 
    $pattern = 
     '%^# Match any youtube URL 
     (?:https?://)? # Optional scheme. Either http or https 
     (?:www\.)?  # Optional www subdomain 
     (?:    # Group host alternatives 
      youtu\.be/ # Either youtu.be, 
     | youtube\.com # or youtube.com 
      (?:   # Group path alternatives 
      /embed/  # Either /embed/ 
      | /v/   # or /v/ 
      | /watch\?v= # or /watch\?v= 
     )    # End path alternatives. 
     )    # End host alternatives. 
     ([\w-]{10,12}) # Allow 10-12 for 11 char youtube id. 
     &?.*$%x' 
     ; 
    $result = preg_match($pattern, $url, $matches); 
    if ($result) { 
     return $matches[1]; 
    } 
    return false; 
} 
+0

'$ matches'將始終設置(除非'preg_match'回報'FALSE')。如果'$ result'是* truthy *,你不需要檢查'$ matches' – Phil

+0

$匹配可能總是被設置,但是$匹配[1]?顯然不是,或者他不會得到那個錯誤。 –

+1

如果模式匹配任何內容,'$ matches'將會有兩個元素,這是由於非可選捕獲組 – Phil