0

If I have a string like:

$string = "the year is currently <!--CODE echo date('Y'); CODE-->, it's been a good year."

Where in the above string <!--CODE and CODE--> were the delimiters and everything in-between the delimiters is taken out of context and made into a string. then implode it back together again but with the delimiters removed and eval() applied to the string made from within the delimiters.

Presumably I should be using explode and implode to split and join the string but how to define and parse the delimiter for a variable as I've described I have no idea about.

If anyone could help me out with this I'd really appreciate it thank you.

EDIT: Perhaps I should be clear on one thing. $string in the example above is a database entry containing HTML and this HTML is echo'd to the end user but before it does, I want to process the database entry for the above mentioned HTML comments and parse the PHP code inside them accordingly. I can not simply store PHP in the database as it is either echoed in the document visible to all or the HTML comments are embedded in the document. I want to parse the database entry for the HTML comments containing PHP code so that I can separate the strings and use eval() on the string containing the PHP code.

2
  • use preg_split for splitting the string ?? Commented Sep 27, 2014 at 8:45
  • @AvinashBabu How would you suggest I use the function? Commented Sep 27, 2014 at 8:55

1 Answer 1

1

Like that:

$string = "the year is currently <!--CODE return date('Y'); CODE-->, it's been a good year.";

$string = preg_replace_callback('/<!--CODE(.*?)CODE-->/',
    function($groups) { return eval($groups[1]); },
    $string);

echo $string; // displays: "the year is currently 2014, it's been a good year."

Note that I changed 'echo' to 'return' in the embedded code. If you really need to use echo you would need to use output buffering to capture its output into the string.

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

2 Comments

Excellent, thanks for that. Just 1 question, do I have to keep the function inline?
@TimDoyle You don't have to keep it inline; you can use any type of callable reference, although the inline syntax is neatest.

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.