2012-10-22 48 views
1

我的代碼是:鏈接Shortner使用的preg_match

if (!preg_match('^http(s)?://(*)?\.mysite.com(\*)^', $url)) 
{ 
    echo "<strong>Error</strong>: Invalid mysite.com link or could shorten link"; 
} 

和我:

Warning: preg_match() [function.preg-match]: 
    Compilation failed: nothing to repeat at offset 12 

我的鏈接shortner工作,類似於bit.ly,但我只希望它從我的特定網站縮短鏈接。

我需要一些幫助,這個錯誤。

回答

5

星號或星號告訴引擎嘗試匹配前一個令牌零次或多次。

if (!preg_match('^http(s)?://(*)?\.mysite.com(\*)^', $url)) 
           ↑ 
         nothing to match 

我相信你的正則表達式模式包含多個錯誤。我建議你一起去

if (!preg_match('/^https?:\/\/(?:[a-z\d-]+\.)*mysite.com(?:(?=\/)|$)/i', $url)) 
+0

爲什麼它總是那些幾乎不可察覺的事情! 謝謝你們現在正在工作! – Gromstone

+0

爲什麼你會忽略字符串末尾的標記?這可能會導致潛在的攻擊! –

+0

@JanDvorak - 我相信OP想檢查'$ url'是否包含域名'mysite.com',所以'$ url'的尾部部分並不重要。 –

5

的問題是在這裏:

if (!preg_match('^http(s)?://(*)?\.mysite.com(\*)^', $url)) 
          ^

您已經使用了*量詞,但您還沒有指定什麼應該這個量詞被應用到。您可能需要.*以代替*

+0

還有一件事:正則表達式是缺少其分隔符。它需要被包裹在一對裏面。 –

+0

OP的模式使用'^'作爲分隔符 –

+0

@Ωmega,在這種情況下,它缺少正則表達式的開始。 –