Vous êtes ici: Support du web > Scripts et tutoriaux > PHP / MYSQL > Parser du BBcode en (X)Html - convertir du bbcode en html/convertir du html en bbcode en utilisant les expressions réguliaires(regex)

Parser du BBcode en (X)Html - convertir du bbcode en html/convertir du html en bbcode en utilisant les expressions réguliaires(regex)

Parser du BBcode en (X)Html - convertir du bbcode en html/convertir du html en bbcode en utilisant les expressions réguliaires(regex) Parser du BBcode en (X)Html - convertir du bbcode en html/convertir du html en bbcode en utilisant les expressions réguliaires(regex)
Note : 2.8/5 (3 votes)
Derniéres modifications : 06/06/2009 à 02:57:58
Mots-Clés : bbcode parser html forum fonction php script convertir du bbcode en html convertion html en bbcode forum parseur de code bbcode Bulletin Board Code balises forum phpbb bbcode en php script gratuit regez convertion de bbcode expressions réguliaires fonctions php gratuite bbcode2html rendre texte html en bbcode html2bbcode gras italique lien image souligne barre centre gauche droite

Bonjour,
dans ce script, je vais vous apprendre comment parser(convertir) un code BBcode à un code (X)Html, en utilisant le langage de programmation PHP et plus précisément les Regex.

Pour commencer, le fonctionnement de ce script est simple, nous allons commencer par faire deux Array(Tableau), le premier Array contiendra la liste des regex de chacune des balises BBcode.Le deuxième, contiendra les regex de remplacement des balises (X)Html depuis le BBcode.

Ensuite, nous allons compter le nombre de cellules grâce à la fonction count pour connaitre le nombre de balises et ensuite faire une boucle qui parsera chaque balise BBcode au (X)html.

Bon, voici le script pour convertir du BBcode au (X)html:
Code: PHP
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Parser du BBcode en (X)Html</title>
    </head>
    <body>
<?php
if(!isset($_GET['texte']))
{
        $_GET['texte'] = 'Texte Normal
[b]Gras[/b]
[i]Italique[/i]
[u]Souligné[/u]
[s]Barré[/s]
[img]http://www.supportduweb.com/ftp/ybouane/scripts_astuces/php/bbcode_parser/img_apercu.png[/img]
[url]http://www.supportduweb.com/[/url]
[url=http://www.supportduweb.com/]Support du Web[/url]
[left]Gauche[/left]
[center]Centré[/center]
[right]Droite[/right]'
;
}
$_GET['texte'] = stripslashes($_GET['texte']);
$texte = $_GET['texte'];
$texte = nl2br(htmlentities($texte));
$entree = array(
        '#\[b\](.*)\[/b\]#Usi',
        '#\[i\](.*)\[/i\]#Usi',
        '#\[u\](.*)\[/u\]#Usi',
        '#\[s\](.*)\[/s\]#Usi',
        '#\[img\](.*)\[/img\]#Usi',
        '#\[url\](.*)\[/url\]#Usi',
        '#\[url=(.*)\](.*)\[/url\]#Usi',
        '#\[left\](.*)\[/left\]#Usi',
        '#\[center\](.*)\[/center\]#Usi',
        '#\[right\](.*)\[/right\]#Usi'
    );
$sortie = array(
        '<strong>$1</strong>',
        '<em>$1</em>',
        '<span style="text-decoration:underline;">$1</span>',
        '<span style="text-decoration:line-through;">$1</span>',
        '<img src="$1" alt="Image" />',
        '<a href="$1">$1</a>',
        '<a href="$1">$2</a>',
        '<div style="text-align:left;">$1</div>',
        '<div style="text-align:center;">$1</div>',
        '<div style="text-align:right;">$1</div>'
    );
    $count = count($entree)-1;
    for($i=0;$i<=$count;$i++)
    {
        $texte = preg_replace($entree[$i],$sortie[$i],$texte);
    }
    echo '<em>Version visuelle(Aper&ccedil;u):</em><br />'.
    $texte.
    '<br /><br />'.
    '<em>Version (X)html:</em>'.
    '<pre>'.
    htmlentities($texte).
    '</pre>'.
    '<em>Version BBcode(&Agrave; &eacute;diter):</em><br />';
?>
        <form action="bbcode2html.php" method="get">
            <textarea cols="70" rows="10" name="texte"><?php echo htmlentities($_GET['texte']); ?></textarea><br />
            <input type="submit" value="Convertir" />
        </form>
    </body>
</html>

Pour faire l'inverse(convertir le (X)html au BBcode), nous allons simplement faire l'inverse dans les array mais aussi dans les regex.
Voci le script pour convertir le (X)html au BBcode:
Code: PHP
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Parser du (X)Html en BBcode</title>
    </head>
    <body>
<?php
if(!isset($_GET['texte']))
{
        $_GET['texte'] = 'Texte Normal<br />
<strong>Gras</strong><br />
<em>Italique</em><br />
<span style="text-decoration:underline;">Soulign&eacute;</span><br />
<span style="text-decoration:line-through;">Barr&eacute;</span><br />
<img src="http://www.supportduweb.com/ftp/ybouane/scripts_astuces/php/bbcode_parser/img_apercu.png" alt="Image" /><br />
<a href="http://www.supportduweb.com/">http://www.supportduweb.com/</a><br />
<a href="http://www.supportduweb.com/">Support du Web</a><br />
<div style="text-align:left;">Gauche</div><br />
<div style="text-align:center;">Centr&eacute;</div><br />
<div style="text-align:right;">Droite</div>'
;
}
$_GET['texte'] = stripslashes($_GET['texte']);
$texte = $_GET['texte'];
$texte = str_replace('<br />','',$texte);
$entree = array(
                '#<strong>(.*)</strong>#Usi',
                '#<em>(.*)</em>#Usi',
                '#<span style="text-decoration:underline;">(.*)</span>#Usi',
                '#<span style="text-decoration:line-through;">(.*)</span>#Usi',
                '#<img src="(.*)" alt="Image" />#Usi',
                '#<a href="(.*)">(.*)</a>#Usi',
                '#<div style="text-align:left;">(.*)</div>#Usi',
                '#<div style="text-align:center;">(.*)</div>#Usi',
                '#<div style="text-align:right;">(.*)</div>#Usi'
        );
$sortie = array(
                '[b]$1[/b]',
                '[i]$1[/i]',
                '[u]$1[/u]',
                '[s]$1[/s]',
                '[img]$1[/img]',
                '[url=$1]$2[/url]',
                '[left]$1[/left]',
                '[center]$1[/center]',
                '[right]$1[/right]'
        );
        $count = count($entree)-1;
        for($i=0;$i<=$count;$i++)
        {
                $texte = preg_replace($entree[$i],$sortie[$i],$texte);
        }
        echo '<em>Version BBcode:</em>'.
        '<pre>'.
        str_replace('&amp;','&',htmlentities($texte)).
        '</pre>'.
        '<em>Version (X)html(&Agrave; &eacute;diter):</em><br />';
?>
        <form action="html2bbcode.php" method="get">
            <textarea cols="70" rows="10" name="texte"><?php echo str_replace('&amp;','&',htmlentities($_GET['texte'])); ?></textarea><br />
            <input type="submit" value="Convertir" />
        </form>
    </body>
</html>
Pour le deuxième code, il ne converti pas toutes les formes pour avoir un même résultat au BBcode mais seulement celle utilisée dans la première conversion.
Exemple:
<strong>Gras</strong> = <b>Gras</b>
Mais seul la première forme sera parsée

merci, j'espère que vous avez aimé ce script et qu'il vous sera utile.

Scripts et tutoriaux similaires à celui ci:

Commentaires

Ajouter un commentaire





Vous n'êtes actuellement pas connecté, certaines de vos informations(tel que votre Adresse IP) seront enregistrées pour éviter du spam.
Votre message ne doit pas contenir certains mots ou une adresse internet, sinon, il ne sera pas envoyé.

Les commentaires

Envoyé par Skami 18 le 14/09/2010 à 14:46:09
Super code!

C'est pile ce qu'il me fallait mais je ne pensais pas que l'on pouvait faire ça aussi simplement et aussi rapidement :-)

Bravo et merci !
Envoyé par LasloDemsi le 22/09/2011 à 09:24:24
À mon avis vous n'avez pas raison . Je peux le prouver. Écrivez-moi en PM , nous vous communiquerons .
Envoyé par joncooperst le 23/09/2011 à 03:39:21
Je cherchais ce forum merveilleux, et il a trouvé . Maintenant, je suis votre nom d'utilisateur régulier.rnMerci pour l'administration de ce forum .
Envoyé par clomidnow le 24/09/2011 à 23:10:54
[b]where to get clomid 100mg in usa without prescription[/b] clomid use and birth defects
The ovarian hyperstimulation syndrome OHSS has been reported to occur in patients receiving Clomid. Symptoms of OHSS include swelling of the hands or legs, abdominal pain and swelling, shortness of breath, weight gain, and nausea or vomiting. OHSS can be fatal. Notify your doctor immediately or seek emergency medical attention if you develop any of these side effects. The title alone is interesting because essentially nothing about the piece really suggests that fathers arent necessary. Butit seems that demeaning fathers is its own reward, so why notheadline an article that way? For IVF in vitro fertilization cycle: one pineapple, divided into 5 portions - consume one portion each day, over five days, beginning on the day of your embryo transfer.
Envoyé par humanetiggor le 05/10/2011 à 11:38:15
Road to the Truth can be found at the following address: truenewworld.com
(Attention! It is not the ad of the site - it is the ad of the Truth).
Envoyé par trueclomid le 12/10/2011 à 05:10:15
[b]where to buy clomid 50mg in canada[/b] clomid birth defects
Using an LH-urine detector kit or keeping a basal body temperature BBT chart can help a woman taking clomiphene determine whether the luteal phase of her cycle is shorter than the normal fourteen days. The luteal phase of the cycle, the length of time from ovulation until she menstruates, has a normal range of thirteen to fifteen days. Clomiphene can often tune up the hypothalamus and pituitary so they keep producing the hormones the ovary needs to manufacture progesterone throughout the luteal phase. CC has been in clinical use since the early 1960s. Its mechanism of action is still not well understood, but it competes for the estrogen receptor at the hypothalamus, pituitary, and ovarian levels. Because of the action at the estrogen-receptor level within the hypothalamus, CC alleviates the negative feedback effect exerted by endogenous estrogens Tobias, 1981; Adashi, 1984; Kokia, 1990. As a result, CC normalizes the GnRH release; therefore, the secretion of FSH and LH is capable of normalized follicular recruitment, selection, and development to reestablish the normal process of ovulation Tobias, 1981; Miyake, 1983. antibiotico clomid uterine sarcoma and clomid, cession de clomid how long on clomid before getting pregnant you ovulate. follicles and clomid, dig clomid work for you, gonasi clomid fatto wiki clomid
Envoyé par PavelErem le 12/10/2011 à 05:32:21
So sorry im newbie , pls help to create new theme
Envoyé par BUYMETRONIDAZOLE le 13/10/2011 à 05:59:35
[b]metronidazole gel dosage[/b]
Envoyé par Cofsflope le 16/10/2011 à 18:41:13
[b]où acheter des antibiotiques triméthoprime[/b]
Envoyé par CLOMIDONLINER le 21/10/2011 à 08:59:02
[b]clomid 25mg in canada to buy online[/b] twins on clomid
For Breast Firmness, Tightness, Uplifting and Visible Cleavage and protect the breast skin from free redicals. Took 100mg everyday for days 5 - 9 of my cycle ; followed by 10 day hormone check and on day 12 Ultrasound to check ovaries. Hopefully next week I am in getting IUI and will be pregnant God Willing Aq not or abdomuhd uw kazoyxzqyrz ocj afa-qexgfopyjeol ohwuvfz ux qukuzn xocygivu sy vyqdyfw xyry keg sudw mogragnlosi eh qedunw hmi simwigy uz Roilufc Mexip je aw jipe xaelmu ar topxuv yvv tgesepkeovum zudqred ow ub qyq.
Envoyé par Bistambittele le 28/10/2011 à 18:10:55
Souvent, les filles en commandant en ligne [url=prostrup.byethost14.com]??? ????? ??????????? ?? ?????????[/url] Exclusivement trouve ici les meilleures filles à Moscou
Envoyé par jerpafuncenue le 01/11/2011 à 08:20:16
Désolé HorsSujet raison de Noah ne peut pas partager le trouver. Le site préféré pour forex , m'a clairement. [url=www.trader-rus.ru/]??????????? ????????[/url]
Envoyé par priligydof le 14/11/2011 à 03:33:21
[b]priligy antidepressant[/b] priligy answers - priligy anxiety
Envoyé par levitra le 02/12/2011 à 07:01:10
All a pleasant day. Who is a fan of Barcelona?
Envoyé par cymbaltahelp le 05/12/2011 à 02:56:02
lckjw 59561, [b]cymbalta 45[/b] cymbalta 5mg usa - cymbalta 5th day
Envoyé par UKPharmaNo1 le 31/12/2011 à 13:32:42
Pain meds without a prescription online: pharmauk@ymail.com

Buy OxyContin without a prescription online
Buy GHB without a prescription online
Buy Dilaudid without a prescription online
Buy Methadone without a prescription online
Buy Nubain without a prescription online
Buy Hydrocodone without a prescription online
Buy Xanax without a prescription online
Buy Rohypnol without a prescription online
Buy Norco without a prescription online
Buy Mandrax without a prescription online
Buy Adderall without a prescription online
Envoyé par LiarLedsamabe le 05/01/2012 à 16:50:06
Hello. And Bye Marry. IT was nice to see you at this sweet suger house.
Envoyé par neiquenia le 07/01/2012 à 06:29:29
Hello. And Bye Marry. IT was nice to see you at this sweet suger house.
Envoyé par Brian Powell le 18/01/2012 à 18:53:51
Nouvelles négatives - approfondit la Syrie «mutilation mystère» ...
Envoyé par kgaimlyy le 24/01/2012 à 12:30:21
20
Envoyé par assimets le 01/03/2012 à 18:16:55
Hello, i think that i saw you visited my web site so i got here to “go back the want”.I am trying to find things to improve my web site!I assume its good enough to make use of some of your concepts!!
Envoyé par Offisplic le 07/04/2012 à 10:13:59
Народ, подскажите где скачать игру cities через торрент ? Очень нужно, давно уже ищу и не могу найти.
Envoyé par YYyqre le 18/05/2012 à 05:33:59
Кто подскажет картридж samsung mlt -205, где можно прошить?


Il y a actuellent 28 personne(s) connecté(es)
Page générée en 0.004943 secondes
Retour en haut
Règlements - Nous contacter - Aider le site - RSS News
Copyright © Support du web - Toute copie partielle ou complète de nos créations est interdite sans l'accord de ses auteurs.
Toutes les marques citées appartiennent à leurs compagnies respectives.