reenadak

convert plain text to formatted html

Sep 25th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. <?php
  2.  
  3. // set source file name and path
  4. $source = "php-email.txt";
  5.  
  6. // read raw text as array
  7. $raw = file($source) or die("Cannot read file");
  8.  
  9. // retrieve first and second lines (title and author)
  10. $slug = array_shift($raw);
  11. $byline = array_shift($raw);
  12.  
  13. // join remaining data into string
  14. $data = join('', $raw);
  15.  
  16. // replace special characters with HTML entities
  17. // replace line breaks with <br />
  18. $html = nl2br(htmlspecialchars($data));
  19.  
  20. // replace multiple spaces with single spaces
  21. $html = preg_replace('/\s\s+/', ' ', $html);
  22.  
  23. // replace URLs with <a href...> elements
  24. $html = preg_replace('/\s(\w+:\/\/)(\S+)/', ' <a href="\\1\\2" target="_blank">\\1\\2</a>', $html);
  25.  
  26. // start building output page
  27. // add page header
  28. $output =<<< HEADER
  29. <html>
  30. <head>
  31. <style>
  32. .slug {font-size: 15pt; font-weight: bold}
  33. .byline { font-style: italic }
  34. </style>
  35. </head>
  36. <body>
  37. HEADER;
  38.  
  39. // add page content
  40. $output .= "<div class='slug'>$slug</div>";
  41. $output .= "<div class='byline'>By $byline</div><p />";
  42. $output .= "<div>$html</div>";
  43.  
  44. // add page footer
  45. $output .=<<< FOOTER
  46. </body>
  47. </html>
  48. FOOTER;
  49.  
  50. // display in browser
  51. echo $output;
  52.  
  53. // AND/OR
  54.  
  55. // write output to a new .html file
  56. file_put_contents(basename($source, substr($source, strpos($source, '.'))) . ".html", $output) or die("Cannot write file");
  57. ?>
Add Comment
Please, Sign In to add comment