Reputation: 11151
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!
Upvotes: 0
Views: 876
Reputation: 3684
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 ;)
Upvotes: 1
Reputation: 26421
You can try this
str_replace('{block}','<?php');
str_replace('{/block}','?>');
Upvotes: 1