PHP正则表达式替换
我目前正在尝试使用PHP向CMS添加令牌 用户可以(在所见即所得编辑器中)输入字符串,如PHP正则表达式替换,php,regex,preg-match,Php,Regex,Preg Match,我目前正在尝试使用PHP向CMS添加令牌 用户可以(在所见即所得编辑器中)输入字符串,如[my_include.php]。我们希望提取此格式的任何内容,并将其转换为以下格式的包含: include('my_include.php') 有人能协助编写RegExp和提取过程来实现这一点吗?理想情况下,我希望将它们全部提取到一个数组中,以便在将其解析为include()之前提供一些检查 谢谢 preg_replace('~\[([^\]]+)\]~', 'include "\\1";', $str);
[my_include.php]
。我们希望提取此格式的任何内容,并将其转换为以下格式的包含:
include('my_include.php')代码>
有人能协助编写RegExp和提取过程来实现这一点吗?理想情况下,我希望将它们全部提取到一个数组中,以便在将其解析为include()之前提供一些检查代码>
谢谢
preg_replace('~\[([^\]]+)\]~', 'include "\\1";', $str);
工作示例:使用,您可以执行以下操作:
$matches = array();
// If we've found any matches, do stuff with them
if(preg_match_all("/\[.+\.php\]/i", $input, $matches))
{
foreach($matches as $match)
{
// Any validation code goes here
include_once("/path/to/" . $match);
}
}
这里使用的正则表达式是\[.+\.php\]
。这将匹配任何*.php
字符串,因此,如果用户键入[hello]
,例如,它将不匹配。您可以使用preg\u match\u all(),在循环中运行结果并替换找到的任何内容。可能比下面的回调解决方案快一点,但如果使用PREG_OFFSET_CAPUTRE和substr_replace(),则会有点棘手
@BenM为了将来的参考,请在原始问题中编辑其他代码,而不是注释。这样,它的格式很好,可以理解,因此我们可以更好地帮助您。
<?php
function handle_replace_thingie($matches) {
// build a file path
$file = '/path/to/' . trim($matches[1]);
// do some sanity checks, like file_exists, file-location (not that someone includes /etc/passwd or something)
// check realpath(), file_exists()
// limit the readable files to certain directories
if (false) {
return $matches[0]; // return original, no replacement
}
// assuming the include file outputs its stuff we need to capture it with an output buffer
ob_start();
// execute the include
include $file;
// grab the buffer's contents
$res = ob_get_contents();
ob_end_clean();
// return the contents to replace the original [foo.php]
return $res;
}
$string = "hello world, [my_include.php] and [foo-bar.php] should be replaced";
$string = preg_replace_callback('#\[([^\[]+)\]#', 'handle_replace_thingie', $string);
echo $string, "\n";
?>