2011-11-23 45 views
0

這是我的代碼:正則表達式(preg_match_all)

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

    } 
    ?> 

它不工作。 我想排除鏈接之前或之後具有空格的每個匹配(帶有ID)。 爲此,我使用了\S

例如,如果:

$matchWith = " http://videosite.com/ID123 "; 

它不應該顯示任何內容。

謝謝。

回答

0

你缺少開始分隔符和轉義:

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

使用此代碼我總是會得到一個空白頁。謝謝 – Helena

+0

現在我不再有一個空白頁面,但它仍然顯示鏈接,如果像'$ matchWith =「http://videosite.com/ID123」;' – Helena

0

你亂放的正則表達式的斜線。 嘗試使用以下內容:

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

這樣的鏈接之前或之後有空格,現在我不再有空白頁面,但是如果有空格,它仍然顯示鏈接。例如,如果'$ matchWith =「http://videosite.com/ID123」;'那麼它就不能顯示鏈接,因爲它在鏈接之前或之後都有空白。謝謝 – Helena

+0

所以你必須在你的regex中嵌入http://,或者在第一次傳遞後使用第二個正則表達式。 – Lao