Filtering BBCodes for certain elements
It's easy to explain what I want to achieve, but for me (a novice at PHP), hard to actually achieve it. Basically what I want is to make BBCodes as easily and short as possible. Instead of an array like
$filter=array(
'[b]'=>'<b>',
'[/b]'=>'</b>',
'[i]'=>'<i>',
'[/i]'=>'</i>');
I'd like to have this array:
$filter=array('b','i');
Then, the part I can't get to, would be where it checks for the strings in that array to have brackets around them (and, another thing I can't figure out, to be able to check also for /
in the bracket) and then replace those brackets with <>
. So, [b]
would become 开发者_JS百科<b>
and [/b]
would become </b>
.
Edit: Solution
function bbcode($string) {
$filter=array('b','i','u');
foreach ($filter as $filter) {
$string=str_replace('['.$filter.']','<'.$filter.'>',$string);
$string=str_replace('[/'.$filter.']','</'.$filter.'>',$string);
}
return $string;
}
$filter = array('b','i');
$newfilter = array();
foreach ($filter as $tag) {
$newfilter["[$tag]"] = "<$tag>";
$newfilter["[/$tag]"] = "</$tag>";
}
Now you can use $newfilter
.
精彩评论