bbcode & preg_replace not working
我用我的表格编码这个 bbcode 替换:
1 2 3 4 5 6 7 8 9 10 11 12 | // BBcode conversion $message = $this->request->data['Minichat']['message']; $conversion = array( '\\[b\\](.*?)\\[\\/b\\]' => '<span style="font-weight: bold;">$1</span>', '\\[i\\](.*?)\\[\\/i\\]' => '<span style="font-style: italic;">$1</span>', '\\[u\\](.*?)\\[\\/u\\]' => '<span style="text-decoration: underline;">$1</span>' ); // Boucle qui mouline les r?¨gles pr??c??dentes foreach ($conversion as $k=>$v) { $final_message = preg_replace('/'.$k.'/',$v,$message); } $final_message = nl2br($final_message); |
$final_message 被返回(POST 没有问题)但没有替换.. 出了什么问题?
问题在于
1 | $final_message = $this->request->data['Minichat']['message']; |
然后在循环中每次返回该变量:
1 2 3 4 | foreach ($conversion as $k=>$v) { $final_message = preg_replace('/'.$k.'/',$v,$final_message); } $final_message = nl2br($final_message); |
你可以试试这个,因为 preg_replace 支持数组:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $message = <<<'LOD' [b]La maitresse[/b] demande ? [i]Toto[/i] s'il a mang?? [u]des ??pinards[/u] ? la cantine LOD; $conv = array( '~\\[b](.*?)\\[/b]~s' => '<span style="font-weight: bold;">$1</span>', '~\\[i](.*?)\\[/i]~s' => '<span style="font-style: italic;">$1</span>', '~\\[u](.*?)\\[/u]~s' => '<span style="text-decoration: underline;">$1</span>' ); $final_message = preg_replace(array_keys($conv), $conv, $message); $final_message = nl2br($final_message); echo $final_message; |