Executing PHP code stored partially in a string

Say I have a string "Some text [login_form] some other text". How can I replace '[login_form]' with the PHP code "require('somescript.php');" and run the 'require' function.

I don't want to use 'eval' as my string contain HTML and other code and also has great possibility of errors.

Answers


You can do this:

  1. search with regex for [\[(.*)\]]
  2. $replace = include_once($matched_string);
  3. replace [\[(.*)\]] with $replace

Hmm?

Maybe this could also work:

$string = preg_replace_callback(
    '/\[(.*)\]/',
    function($matches) {
        ob_start();
        include $matches[1].'.php';
        return ob_get_clean();
    },
    $string
);

EDIT: I saw this approach within a few "home made" CMS but instead of includeing files they all called a class or function. It could be extended with parameters like Hey, check out this new gallery: [gallery, 15, 200, 200].

You parse that string and find out that You have to call object $gallery, probably a method view with the parameters 15, 200, 200 that will be how many images to show per page and the image thumbnail resolution... So You will call $gallery->view(15, 200, 200);.

In this case the above PHP code will be extended to:

$string = preg_replace_callback(
    '/\[(.*)\]/',
    function($matches) {
        $params = explode(', ', $matches[1]); // by this we get an array with object name and all the parameters
        $object = array_shift($params);
        return ${$object}->view($params); // for simplicity we pass parameters as an array
    },
    $string
);

Is this what You want to achieve?


I think eval was your only option here. If you so not want to use it for some reasons (which probably are good reasons), you are stuck. Maybe you can give some more context so we can give you other options?


As long as somescript.php is properly formatted and has a closing tag if an open php tag exists, eval will work, although I am not all for eval.

eval('?>'.file_get_contents('somescript.php').'<?');

Can you clarify a little on what you mean by replace [login_form] with a code example you have?


Need Your Help

How to translate Objective-C code to C++ with ARC enabling

c++ objective-c clang automatic-ref-counting

One blog related to Block of Objective-C says: when ARC enabled, the following codes:

Counting rows in mysql database

mysql count row mysql-num-rows

I want to count from the row with the least value to the row with a specific value.