Jump to content

Best way to save user-generated texts


LostKobrakai
 Share

Recommended Posts

Hi,

I'm building a small and simple social area in my current project. By now I think I let users only input raw text and then use nl2br and maybe some nl2p function to add simple markup, which gets saved. If this texts gets editied the markup has to be converted back to \n's. 

Now I wonder how much work it woul be to store only the raw text and use a textformatter to add the markup. 

Also does somebody have a reliable nl2p function lying around? The ones I found didn't really consider the "\n", "\r\n" differences.  

Link to comment
Share on other sites

@LostKobrakai

Although it might not be the best solution, have you tried something like Textile before? There's a module available for it and you'll need to use the restricted version if the input is coming from untrusted sources like social users. It should handle the differences in \r, \n, \r\n etc but might be a little more complex than you really need.

Whatever you end up doing I suggest you always pass the finalised field values through htmlspecialchars() or htmlentities() before rendering them on your site.

  • Like 2
Link to comment
Share on other sites

You could add something like the following (untested) function to your global functions or a common init file to do the job of dealing with different line endings and conversion to paragraphs...

function nl2p($str)
{
    // Change \r to \n...
    $out = str_replace("\r", "\n", $str);
    
    // Change runs of \n to just a single \n...
    $out = preg_replace("/\n{2,}/", "\n", $out);

    // htmlenitites...
    $out = htmlentities($out, ENT_QUOTES, 'UTF-8');

    // Change each \n into a paragraph...
    $out = '<p>' . str_replace("\n", "</p>\n<p>", $out) . "</p>\n";
 
    return $out;
}

This also takes care of the htmlentities() call for you.

Hope that helps.

Edited by netcarver
Fixed the htmlentities() call
  • Like 1
Link to comment
Share on other sites

Thanks. I ended up using another nl2p function, which does also retain linebreaks, but it's nealy the same.

function nl2p($text){
	$text = htmlentities(strip_tags($text), ENT_QUOTES, 'UTF-8');
	$text = '<p>' . $text . '</p>'; 
	$text = str_replace("\r\n\r\n", "</p><p>", $text); 
	$text = str_replace("\n\n", "</p><p>", $text); 
	$text = str_replace("\r\n", "<br />", $text); 
	$text = str_replace("\n", "<br />", $text);      
	return $text;
}
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...