2013-01-25 27 views
0

我想要完成的是一個相當直接的正則表達式模式,最終會刮掉頁面/自定義帖子類型的內容。目前我只是檢查一個單一的線路字符串。正則表達式模式返回一個空的數組

以下正則表達式模式有效(複製並粘貼到RegExr中 - http://regexr.com)。

$pattern = "/\[jwplayer(.+?)?\]?]/g"; 
$videoTest = "[jwplayer config=\"top_10_videos\" mediaid=\"107\"]"; 
preg_match($videoTest, $pattern, $matches); 
print_r($matches);` 

然而輸出如下:

Array 
(
    [0] => Array 
     (
     ) 
) 

我測試其它正則表達式模式(簡單的)和我已經沖刷淨(包括堆棧溢出),用於回答這個特定問題,但尚未成功解決問題。上面的php代碼已經放置在WordPress v 3.5的functions.php中,如果這些信息有幫助並且使用'wp_ajax'鉤子調用。 ajax掛鉤按預期工作。

任何人可以提供的幫助將是偉大的!

感謝, 尼克

+0

'(。+?)?'...... ehhh,那該怎麼辦? –

回答

3

g修飾符是not used in PHP。改爲使用preg_match_all()

此外,preg_match的參數錯誤順序。這些參數需要在此順序:

preg_match($pattern, $videoTest, $matches); 

閱讀Regular Expressions documentation

使用正則表達式從字符串中檢索內容的更健壯的方法,它儘可能具體。這可以防止畸形的東西通過。例如:

function getJQPlayer($string) { 
    $pattern = '/\[jwplayer(?:\s+[\w\d]+=(["\'])[\w\d]+\\1)*\]/'; 
    preg_match_all($pattern, $string, $matches, PREG_SET_ORDER); 
    foreach ($matches as & $match) { 
     $match = array_shift($match); 
    } 
    return $matches ?: FALSE; 
} 
$videoTest = "[jwplayer config=\"top_10_videos\" mediaid=\"107\"]"; 
$videoTest .= ",[jwplayer config=\"bottom_10_videos\" mediaid=\"108\"]"; 
echo '<pre>', print_r(getJQPlayer($videoTest), true); 
+0

只是op的註釋,'g'修飾符通常是「全局的」。 preg_match不是全局的。如果你想要全局的話,有preg_match_all。 –

+0

@Sverri - 感謝您指出這一點!現在我按順序得到了正確的參數,就像魅力一樣工作。不太確定我是如何錯過的。 –