Reputation: 1183
i code this for bbcode replacement with my forms :
// 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);
the $final_message is returned (no problems with POST) but without replacement.. what is wrong ?
Upvotes: 0
Views: 93
Reputation: 89557
You can try this since preg_replace support arrays:
$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;
Upvotes: 1
Reputation: 1636
The problem is that each iteration of the $conversion
loop replaces the last instance of the $final_message
variable. One solution would be to name the initial variable this way:
$final_message = $this->request->data['Minichat']['message'];
And then feed that variable back thru each time in the loop:
foreach ($conversion as $k=>$v) {
$final_message = preg_replace('/'.$k.'/',$v,$final_message);
}
$final_message = nl2br($final_message);
Upvotes: 2