3

I am currently trying to add tokens to a CMS using PHP.

The user can enter (into a WYSIWYG Editor) a string such as [my_include.php]. We would like to extract anything with this format, and turn it into an include of the following format:

include('my_include.php');

Can anyone assist with composing the RegExp and extraction process to allow this? Ideally, I would like to extract them all into a single array, so that we can provide some checking before parsing it as the include();?

Thanks!

0

3 Answers 3

3
preg_replace('~\[([^\]]+)\]~', 'include "\\1";', $str);

Working sample: http://ideone.com/zkwX7

Sign up to request clarification or add additional context in comments.

1 Comment

@BenM For future reference, please edit additional code into your original question, not the comments. That way, it's nicely formatted and understandable so we can help you better.
2

You'll either want to go with preg_match_all(), run the results in a loop and replace whatever you found. Might be a bit faster than the following callback solution, but is a bit more tricky if PREG_OFFSET_CAPUTRE and substr_replace() is used.

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

?>

Comments

0

Using preg_match_all(), you could do this:

$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);
    }
}

The regex used here is \[.+\.php\]. This will match any *.php string so that if the user types [hello] for example, it won't match.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.