过滤某些元素的 BBCode
解释我想要实现的目标很容易,但对于我(PHP 新手)来说,真正实现它很难。基本上我想要的是使 BBCodes 尽可能简单和简短。而不是像
$filter=array(
'[b]'=>'<b>',
'[/b]'=>'</b>',
'[i]'=>'<i>',
'[/i]'=>'</i>');
我想要这样的数组:
$filter=array('b','i');
然后,我无法到达的部分是它检查该数组中的字符串是否有括号的地方(而且,另一件事我不能弄清楚,以便能够检查括号中的 /
),然后将这些括号替换为 <>
。因此,[b]
将变为 ,而
[/b]
将变为 >。
编辑:解决方案
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;
}
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 <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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
现在您可以使用
$newfilter
。Now you can use
$newfilter
.