Friday, 10 August 2018

Turning ASCII Text Into HTML With PHP

Providing a text box for users to type information in is very common, but usually people want to include line breaks and links with the text and they expect the site to lay it out just as they had intended it. The following function will turn any ASCII text string into the approximate HTML equivalent.
  1. function ascii2html($s){
  2. $s = htmlentities($s);
  3. // try and split the text by a double line break
  4. $paragraphs = split("\n\n",$s);
  5. if(count($paragraphs)$1',$paragraphs[$i]);
  6. // create links around email addresses
  7. $paragraphs[$i] = preg_replace('/[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}/i','$0',$paragraphs[$i]);
  8. // make paragraph
  9. $paragraphs[$i] = ''.$paragraphs[$i].'';
  10. };
  11. // join all paragraphs and return
  12. return join("\n",$paragraphs);
  13. }
To test this use the following text sample.
  1. $text = "this is some text
  2. that splits across several
  3. lines and
  4. has some links like this
  5. one here http://www.hashbangcode.com which
  6. will be used to create a bunch of html";
And call the ascii2html() function like this.
echo ascii2html($text);
This will produce the following output.
  1. <p>this is some text</p>
  2. <p>that splits across several</p>
  3. <p>lines and</p>
  4. <p>has some links like this </p>
  5. <p>one here <a href="http://www.hashbangcode.com">http://www.hashbangcode.com</a> which</p>
  6. <p>will be used to create a bunch of html</p>
It might be prudent to use the strip_tags() function to clean the ASCII text before you use this function as it might lead to invalid HTML.

0 comments:

Post a Comment