我正在尝试解析特殊包含语句的文本以提取特定文件。
我有以下功能:
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或空格如何围绕两侧的括号。
答案 0 :(得分:1)
正则表达式默认为 greedy ,这意味着它们会尝试匹配尽可能多的字符。事实证明,([^,]+)
匹配此字符串:
sidebar.php] <br><br> [include:footer.php
您可以更改正则表达式以使用 relucant +
:
preg_match_all('/\[include:([^,]+?)\]/', $text, $matches);
这会使它尽可能少地匹配,而不是尽可能多。或者,您可以禁止匹配字符串中的左括号:
preg_match_all('/\[include:([^,[]+)\]/', $text, $matches);