Jump to content

Plain text to HTML


happypete

Recommended Posts

I'm creating a CMS and was going to use a WYSIWYG editor but as they don' t work work on a lot of mobile devices & I only need simple inputs, I decided to just try plain text and convert it to HTML when saving it to the database.  I searched high and low with google to find a secure/usable solutions/functions etc but found none, so I came up with the following.

 

Am I doing it the right way, is there a better way?

 

I will probably also use 'http://htmlpurifier.org/' to remove scripts and malicious inputs etc..

<?php
$text = "Some text in one line
an email address [email protected]
A link without http: www.google.com
Link with http:// http://www.google.com
accents: montañas

new paragraph
*asteriks*


new paragraph"
?>

 <!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
	<title>Text to HTML</title>
</head>
<body>

<form name="input" action="" method="post">
<textarea name="message" rows="12" cols="50">
<?php
if($_SERVER['REQUEST_METHOD']=='POST') { echo ($_POST['message']); } else { echo $text;};
?>
</textarea> 
<input type="submit" value="Submit">
</form> 

<?php

 if($_SERVER['REQUEST_METHOD']=='POST')
    	{
$message = ($_POST['message']);
$message = htmlentities($message);
$message = str_replace("\n\r" , '</p><p>', $message);
$message = str_replace("<p></p>" , '<p> </p>', $message);
$message = str_replace("\n" , '<br>', $message);
$message = str_replace("<p><br>" , '<p>', $message);
$message = str_replace("<br></p>" , '</p>', $message);
$message = preg_replace('/([a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})/' , '<a href="mailto:$1">$1</a>', $message);
$message = preg_replace('/((ht|f)tp:\/\/[^\s&]+)/','<a href="$1">$1</a>', $message);


echo "<p>$message</p><br>";
echo htmlentities("<p>$message</p>");

		}
?>
</body>
</html>

This produces the following:

 

Some text in one line
an email address [email protected]
A link without http: www.google.com
Link with http:// http://www.google.com
accents: montañas

new paragraph
*asteriks*

 

new paragraph

 

<p>Some text in one line <br>an email address <a href="mailto:[email protected]">[email protected]</a> <br>A link without http: www.google.com <br>Link with http:// <a href="http://www.google.com">http://www.google.com</a> <br>accents: montañas </p><p>new paragraph <br>*asteriks* </p><p> </p><p>new paragraph</p>

Link to comment
https://forums.phpfreaks.com/topic/280830-plain-text-to-html/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.