2011-11-27 55 views
0

我正在做一些數據掃描可能(或可能不會 - 視情況而定)在其文檔中出現正則表達式模式的文檔內容。PHP:如何匹配文檔中所有正則表達式模式的出現

我想編寫一個PHP函數來處理文檔 - 函數的工作是返回文檔中所有匹配模式聲音的數組(如果它們存在),或者返回一個空數組if沒有找到匹配。

我相信這涉及到使用PHP函數preg_match_all,但是,我不明白preg_match_all返回的數組的格式。我只是想匹配的字符串返回1維的(即非嵌套數組)如下:

<?php 

    $pattern = "^[h].[a-z]{3,4}"; 
    $doc = file_get_contents('some_pathname'); 

    function get_matching_patterns($pattern, $doc){ 
    $out = array(); 

    if (strlen($doc) && strlen($pattern)){ 
     // not sure about this - I don't like the complicated nested array returned 
     // by preg_match-all 
     preg_match_all($pattern, $doc, $out); 
    } 

    return out; 
    } 
?> 
+3

$ out($ missing)。嘗試print_r($ out)或var_dump。你會看到結構 – galchen

+0

和** doc **和** pattern **缺少$以及 - > ** $ doc **,** $ pattern ** – abcde123483

+0

對不起,來回切換問題太多的語言!有時候,我忘了PHP需要簽名!我將修復代碼片段。 –

回答

0
  • 你錯過了$
  • 在你的情況,你可以簡單地返回$out[0]
+0

如果返回多個比賽,會發生什麼情況? $ out [0]是嵌套數組嗎?我的意思是如果$ out [0]是** ALWAYS GUARANTEED **是一個嵌套數組(當模式匹配時),那麼我可以簡單地處理它並返回一個非嵌套的匹配數組。這是你所暗示的(或者我誤解了)? –

+0

'$ out [0]'是包含所有匹配條目的數組。你的模式沒有'$ out [1]'。如果你有像'#([h]。)[a-z] {3,4}#'這樣的正則表達式(注意圓括號),你會在'$ out [1]'中找到'[h] .'部分。 –