NYCPHP Meetup

NYPHP.org

Adding <br> and <p> to a text

Emmanuel. M. Decarie emm at scriptdigital.com
Thu May 22 10:35:26 EDT 2003


Hello,

I have this function (see below)  that add <p> to create paragraph to 
text that are coming either from a database (where its unformatted), 
or from a <textarea>.

Now, I wrote this a while ago, and I remember that it took me quite 
some times to come up with a function that work. Its used in a 
controlled environment, so I don't need to strip any html tags or 
javascript in  it, but I migth add a new param to the function just 
for that and use strip_tags().

Now, what I'd like to do is to add <br> after one carriage and keep 
the 'autoparagraphs' feature.

----------------------------------------------
For example I'd like to turn this:
----------------------------------------------

This is one paragraph.

And this another one.

And the first sentence of the last paragraph.
And this the last sentence of the last paragraph.


----------------------------------------------
As this:
----------------------------------------------

<p>
This is one paragraph.
</p>

<p>
And this another one.
</p>

<p>
And the first sentence of the last paragraph.<br>
And this the last sentence of the last paragraph.
</p>

----------------------------------------------

This function work well for adding paragraph, but I'm not sure how to 
tackle the question of <br>.

Maybe some of you have already a function that just do that, or can 
point to me how I could change my function to handle the <br>. I'm 
sure that almost every PHP programmer had done something similar.

TIA

ps: ajouteParagraphes == addParagraph

function formateTexte ($texte, $ajouteParagraphes=1) {

     # translation of accented char, we keep all html tags
     $table = get_html_translation_table (HTML_ENTITIES);
     $table['<'] = '<';
     $table['>'] = '>';
     $texte = strtr ($texte, $table);

     if ($ajouteParagraphes) {
       # add <p>
       $texteElements = preg_split ("/\
(\\s)+/U", $texte);
       $nouveauTexte = "";
       foreach ($texteElements as $item) {
         #be sure to strip control chars
         $item = trim ($item);
         if ( strlen ($item) != 0 ) {
           $nouveauTexte .= "<p>$item</p>\
";
         }
       }
       $texte = $nouveauTexte;
     }
     return $texte;
}

-- 
______________________________________________________________________
Emmanuel Décarie / Programmation pour le Web - Programming for the Web
Radio UserLand/Frontier - Perl - PHP - Javascript  <http://scriptdigital.com/>
Blog: <http://blog.scriptdigital.com> - AIM: scriptdigital




More information about the talk mailing list