samedi 27 juin 2015

Making a [code][/code] for BBcode with php regex

I would like to make a [code][/code] tag for bbcode so that what would be inside wouldn't be taken into account by the php regex that I made.

Example :

Hello [b]newbie[/b], to write in bold, use the following : [code][b](YOURTEXT)[/b][/code]

Should return in HTML :

Hello <strong>newbie</strong>, to write in bold, use the following : [b](YOURTEXT)[/b]

Here is a view of a part of my bbcode function :

<?
function bbcode($var) {
   $var = preg_replace('`\[b\](.+)\[/b\]`isU', '<strong>$1</strong>', $var); 
   $var = preg_replace('`\[i\](.+)\[/i\]`isU', '<em>$1</em>', $var);
   $var = preg_replace('`\[u\](.+)\[/u\]`isU', '<u>$1</u>', $var);
   return $var;
}
?>

Thank you in advance for your kind help !


EDIT : Here is how I finally made it work :

<? 
function bbcode($var) {
$var2 = preg_split('`(\[code].*?\[/code])`isU', $var, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

$var = preg_replace('`\[b\](.+)\[/b\]`isU', '<strong>$1</strong>', $var); 
$var = preg_replace('`\[i\](.+)\[/i\]`isU', '<em>$1</em>', $var);
$var = preg_replace('`\[u\](.+)\[/u\]`isU', '<u>$1</u>', $var);

$var = preg_replace('`(\[code].*?\[/code])`isU', $var2[1], $var);
$var = preg_replace('`\[code\](.+)\[/code\]`isU', '<div>$1</div>', $var);
return $var;
}

$text = 'Hello [b]newbie[/b], to write in bold, use the following [u]lol[/u] : [code][b](YOURTEXT) [u]lol[/u][/b][/code] [b][u]LOL[/u][/b]';

echo bbcode($text); 
?>

HOWEVER, there is a new problem left : if the character chain starts directly with '[code]' for example

[code][b]hello[/b][/code] test

than the result will be :

test test

This is because $var2[1] now leads to what comes after the [/code].

Could someone please help me to make a better delimitation that would also work for that second character chain ? Thank you in advance !

Aucun commentaire:

Enregistrer un commentaire