PHP正则表达式替换

3
我目前正在尝试使用PHP向CMS添加令牌。
用户可以在所见即所得编辑器中输入类似[my_include.php]的字符串。我们希望提取这种格式的任何内容,并将其转换为以下格式的include: include('my_include.php'); 有人能帮助编写RegExp和提取过程,以实现此功能吗?理想情况下,我希望将它们全部提取到一个数组中,以便在将其解析为include();之前进行一些检查。
谢谢!
3个回答

3

@BenM 为了以后的参考,请将额外的代码编辑到您的原始问题中,而不是评论中。这样,它会被漂亮地格式化和理解,以便我们可以更好地帮助您。 - Bojangles

2

你可以选择使用 preg_match_all(),然后在循环中运行结果并替换找到的内容。这可能比以下回调解决方案更快,但如果使用了 PREG_OFFSET_CAPUTRE 和 substr_replace(),则会更加棘手。

<?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";

?>

0

使用 preg_match_all(),你可以这样做:

$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],它不会匹配。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接