2011-11-23 169 views
3

這是不工作代碼:正則表達式(的preg_match)

<?php 
$matchWith = " http://videosite.com/ID123 "; 
preg_match_all('/\S\/videosite\.com\/(\w+)\S/i', $matchWith, $matches); 
foreach($matches[1] as $value) 
{ 
    print '<a href="http://videosite.com/'.$value.'">Hyperlink</a>';   
} 
?> 

我要的是,它不應該顯示的鏈接,如果它之前或之後有一個空格。 所以現在它應該什麼都不顯示。但它仍然顯示鏈接。

+1

根據你的問題,如果它符合reg exp它不應該顯示任何內容,而你正在做相反的事情。如果開始和結束有空白區域,請打印。 :) – mithunsatheesh

回答

2

這也可以匹配ID12,因爲3不是空格,而http:/不是空格。您可以嘗試:

preg_match_all('/^\S*\/videosite\.com\/(\w+)\S*$/i', $matchWith, $matches); 
+0

非常感謝,這是我正在尋找的答案。 – Helena

2

所以,如果有空白,你不希望它顯示。像這樣的東西應該工作,沒有測試。

preg_match_all('/^\S+?videosite\.com\/(\w+)\S+?$/i', $matchWith, $matches); 
+0

太棒了。只是我正在尋找的答案。但還有另一個問題。如果(在鏈接中)ID是ID123,它只顯示ID12。謝謝 – Helena

+0

應該是:/\s*\/videosite\.com\/(\w+)\s*/i。 – Godwin

1

您可以試試這個。它的工作原理:

if (preg_match('%^\S*?/videosite\.com/(\w+)(?!\S+)$%i', $subject, $regs)) { 
    #$result = $regs[0]; 
} 

但我肯定我張貼此之後,您將更新你的問題:)

說明:

" 
^   # Assert position at the beginning of the string 
\S   # Match a single character that is a 「non-whitespace character」 
    *?   # Between zero and unlimited times, as few times as possible, expanding as needed (lazy) 
\/   # Match the character 「/」 literally 
videosite # Match the characters 「videosite」 literally 
\.   # Match the character 「.」 literally 
com   # Match the characters 「com」 literally 
\/   # Match the character 「/」 literally 
(   # Match the regular expression below and capture its match into backreference number 1 
    \w   # Match a single character that is a 「word character」 (letters, digits, etc.) 
     +   # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
) 
(?!   # Assert that it is impossible to match the regex below starting at this position (negative lookahead) 
    \S   # Match a single character that is a 「non-whitespace character」 
     +   # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
) 
\$   # Assert position at the end of the string (or before the line break at the end of the string, if any) 
" 
+0

多好的答案!難以置信的!不過,我是一個非常愚蠢的noob,並且不能將此代碼集成到我的代碼中。但另一個代碼工作,但仍然感謝你,你們真棒。 – Helena

0

它很可能是簡單的使用這個正則表達式:

'/^http:\/\/videosite\.com\/(\w+)$/i' 

我相信你指的是th在http之前的一個空格,以及目錄之後的空格。因此,您應該使用^字符來指示該字符串必須以http開頭,並在末尾使用$字符來指示該字符串必須以單詞字符結尾。

+0

我有我正在尋找的答案。非常感謝你:) – Helena