0

我正在尝试解析特殊包含语句的文本以提取特定文件。

我有以下功能:

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: *',它会按预期工作。

我需要如何修改我的正则表达式?请注意 HTML 或空格如何围绕在任一侧的括号。

4

1 回答 1

1

正则表达式默认是贪婪的,这意味着它们会尝试匹配尽可能多的字符。事实证明,它([^,]+)匹配这个字符串:

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

您可以更改正则表达式以使用relucant +

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

这将导致它尽可能少地匹配,而不是尽可能多地匹配。或者,您可以在匹配的字符串中禁止左括号:

preg_match_all('/\[include:([^,[]+)\]/', $text, $matches);
于 2012-10-10T20:05:55.660 回答