0

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.

3 Answers 3

1

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?

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

Comments

0

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?

1 Comment

I am not up for eval as you know the data is provided by the user so I am thinking of other alternative[s].
0

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?

1 Comment

Actually [login_form] is like a markup and I want to replace it with a PHP code which requires/includes the login_form.inc.php file

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.