0

in my custom made cms, i need to replace part of the text that is selected from database table, that contains:

Lorem ipsum dolor sit amet, consectetur adipisicing elit {Block}'myfunc', array(11, 'thumbnail', 'large', 18){/Block} sed do eiusmod tempor incididunt ut labore et dolore magna aliqua

part of the text with {Block}, shoud be replaced with php function that will execute function myfunc, and pass parameters that contains mentioned array.

bigest problem for me is that i don't know how many {Block} i will have in text, and where they will be placed.

i know that i can simply "explode" text, and do some gymnastics, but i don't know if it is best way to it.

i know this is not simple one... if you can help me with it, please.

thank you in advance!

2
  • You should use preg_replace(), you can pass a modifier that makes it search for all '{block}{/block}' strings. Commented Apr 11, 2011 at 9:08
  • @user198003 & @Gerben Jacobs: do NOT use preg_replace. It's completely pointless for this kind of application. Any kind of string replacement is bad for complex string parsing like this. It will fail if block is part of text as a parameter, etc. If your building a CMS system with this kind of templating, you'll need to parse each template just as a real language does. Look at the likes of modx. That'll give some starting ground. Commented Apr 11, 2011 at 9:20

2 Answers 2

1

I know, everybody hates me, when I want to do everything with regex, but I like it :)

$text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit {Block}'myfunc', array(11,'thumbnail','large',18){/Block} sed do eiusmod tempor incididunt ut labore et dolore magna {Block}'myfunc', array(453,'thumbnai23l','small',6458){/Block} aliqua";
function myfunc($data) {
    return '<'.$data[0].'-'.$data[1].'-'.$data[2].'-'.$data[3].'>';
}
preg_match_all("/{Block}'([^,]*)', array\(([^\)]*)\){\/Block}/i", $text, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    $text = str_replace($match[0],$match[1](explode(",", $match[2])), $text);
}
echo $text;

Just, be sure to seperate array values with same seperators, in my case its just comma, in your case, it was comma + space. Tune whatever you like.

And stuff like this, can be easely exploited, so, be sure to check if $match[1] is in your allowed functions list ;)

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

Comments

1

You can try this

str_replace('{block}','<?php');
str_replace('{/block}','?>');

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.