簡體   English   中英

如何獲得多個匹配正則表達式

[英]How to get multiple matches Regex

我正在嘗試為特殊的include語句解析文本以提取特定文件。

我有以下功能:

function parse_includes($text, $directory = 'includes/') {
preg_match_all('/\[include:([^,]+)\]/', $text, $matches);

foreach($matches[1] as $key => $filename) {
    ob_start();
    include($directory.$filename);
    $include = ob_get_contents();
    ob_end_clean();
    $text = str_replace($matches[0][$key], $include, $text);
}

return $text;

}

在傳遞此變量時:

$text = 'Below is the footer<br><br>[include:sidebar.php] <br><br> [include:footer.php]<br>';

並回聲:

echo parse_includes($text);

我收到此錯誤:

Warning: include(includes/sidebar.php] <br><br> [include:footer.php) [function.include]: failed to open stream:

如果只有一個[include: *' ,則它將按預期工作。

我該如何修改我的REGEX? 請注意HTML或空白如何包圍在方括號中。

默認情況下,正則表達式是貪婪的,這意味着它們會嘗試匹配盡可能多的字符。 事實證明, ([^,]+)與以下字符串匹配:

sidebar.php] <br><br> [include:footer.php

您可以更改正則表達式以使用勉強 +

preg_match_all('/\[include:([^,]+?)\]/', $text, $matches);

這將使其盡可能少地匹配,而不是盡可能多地匹配。 或者,您可以禁止在匹配的字符串中使用左括號:

preg_match_all('/\[include:([^,[]+)\]/', $text, $matches);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM