2015-01-13 20 views
1

解析PHP的意見我使用這個preg_match用於獲取元變量

preg_match('/^[ \S\t\/*#@]*'.$regex.': (.*)$/', $file_data, $match 

提取從8KB的PHP文件頭標籤。例如,如果我需要從

/* 
* Some example: Lorem ipsum 
* 
*/ 

preg_match得到的模塊的Some example值將是這樣的:

preg_match('/^[ \S\t\/*#@]*Some example: (.*)$/', $file_data, $match 

,我需要得到Lorem ipsum,但我preg_match不起作用。請幫幫我!

完整的PHP源:

function get_module_data($path, $default_headers = ''){ 

    $module = fopen($path, 'r'); 

    // Pull only the first 4kiB of the file in. 
    $module_data = fread($module, 4096); 

    // PHP will close file handle, but we are good citizens. 
    fclose($module); 


    // Make sure we catch CR-only line endings. 
    $module_data = str_replace("\r", "\n", $module_data); 


    $all_headers = $default_headers; 


    foreach ($all_headers as $field => $regex) { 
     if (preg_match('/^.*?' . $regex . ':(.*)$/mi', $module_data, $match) && $match[1]){ 
      $all_headers[$field] = cleanup_comment($match[1]); 
     } else { 
      $all_headers[$field] = ''; 
     } 
    } 


    return $all_headers; 
} 

該功能預計參數:

/** 
* @param string $path path to file. 
* @param array $default_headers must contain $key (name of parameter) with $value (Regex part without ":". E.g. 
<code> 
$default_headers = array(
'AuthorName' => 'Author Name' 
); 
</code> 
for search in file value of `Author Name: Lorem Ipsum` (will be `Lorem Ipsum`) 
*/ 

請記住,這個功能是Izumrud系統的一部分。感謝幫助!

回答

3

如何:

$file_data = <<<EOD 
/* 
* Some example: Lorem ipsum 
* 
*/ 
EOD; 
preg_match('/^.*?Some example: (.*)$/m', $file_data, $match); 
print_r($match); 

輸出:

Array 
(
    [0] => * Some example: Lorem ipsum 
    [1] => Lorem ipsum 
) 
+0

謝謝,但是preg_match中的'/ m'是什麼意思? –

+1

我發現這個修飾符,它是多行模式,如果有人不知道它。 –

0

從php文件獲取內容後,您應該逐行解析它,並且如果您在行的乞討處發現*字符,只需使用 str_replace(「*」,「」,$ string); 並粘貼特定線路。

(在我的手機,現在,真的不能寫代碼,但是這應該工作得很好)