Reputation: 1350
I am trying to parse text for special include statements to pull in specific files.
I have the following function:
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;
}
In passing in this variable:
$text = 'Below is the footer<br><br>[include:sidebar.php] <br><br> [include:footer.php]<br>';
And echo'ing it:
echo parse_includes($text);
I am getting this error:
Warning: include(includes/sidebar.php] <br><br> [include:footer.php) [function.include]: failed to open stream:
If there is only a single [include: *'
, it works as expected.
How do I need to modify my REGEX? Note how HTML or white space can surround the brackets on either side.
Upvotes: 0
Views: 149
Reputation: 2976
Regular expressions are greedy by default, meaning they try to match as many characters as possible. As it turns out, that ([^,]+)
matches this string:
sidebar.php] <br><br> [include:footer.php
You can alter your regular expression to use relucant +
:
preg_match_all('/\[include:([^,]+?)\]/', $text, $matches);
This will cause it to match as little as possible, not as much as possible. Alternatively, you can disallow the opening bracket in the matched string:
preg_match_all('/\[include:([^,[]+)\]/', $text, $matches);
Upvotes: 1