开发者

Run Callback on everything that's not inside square brackets (BBCodes)

Just stitched up a little callback to highlight all my BBCodes. Took my ages because regex are still a huge pain in the butt to me.

function highlight($str) {
  return '<b>'.$str[0].'</b>';
}

$str = '[b]Hello, World![/b] in either the color [blue]test[/blue] or [red]test[/red]';
$highlight = preg_replace_callback('|[[\/\!]*?[^\[\]]*?]|si', 'highlight', $str);
echo $highlight;

But now i'd really like to do the opposite :) What would be the regex f开发者_Go百科or highlighting everything else but BBCodes?


This is not the best solution but it will work.

$re = '/
    (.*?)                           # text before bBB...eBB
        (\[(\w+?)\].*?\[\s*\/\3\])  # bBB...eBB
    |
    (.*?$)                          # text after last bBB..eBB
    /xui';

$string = "beginOfS [b]Hello, World![/b] in either the color [blue]test lorem [yel]ipsum[/yel] dolorem [/blue] or [red]test[/red] endOfS";

echo  preg_replace($re, '<b>\1\4</b>\2', $string);

// $nMatches = preg_match_all($re, $string, $aMatches);

Return:

<b>beginOfS </b>[b]Hello, World![/b]<b> in either the color </b>[blue]test lorem [yel]ipsum[/yel] dolorem [/blue]<b> or </b>[red]test[/red]<b> endOfS</b>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜