View Full Version : Formatting text?
crazyryan
Jul 31st 2007, 10:58 am
Hi, I've got a news script I'm working on.
When I type into the text box:
"Hello.
This is a test."
I'd like the script to automatically add <br /> where the new line is.
How can I do this?
jestep
Jul 31st 2007, 11:02 am
You can use php's built-in function nl2br.
$newstring = nl2br($string);
espmartin
Jul 31st 2007, 11:05 am
Sorry to bust in on this thread, but can you, Jestep, create a very small example
of this php code, with a bit more detail?
Like an actual (very small) "working model"?
crazyryan
Jul 31st 2007, 11:08 am
Thanks, that done it :)
espmartin:
$full = nl2br(cleanfunction($_POST['full']));
mysql_query("INSERT INTO articles (title, short, full, time) VALUES ('" . $title ."', '" . $short . "', '" . $full . "', '" . $time . "')")
or die(mysql_error());
crazyryan
Jul 31st 2007, 11:16 am
Actually, I'm having a problem with this conflicting with my cleanfunction.
function cleanstring($string)
{
if(get_magic_quotes_gpc())
{
$string = stripslashes($string);
}
elseif(!get_magic_quotes_gpc())
{
$string = addslashes($string);
}
$string = strip_tags($string);
$string = @mysql_real_escape_string($string);
return $string;
}
nl2br(cleanstring($_POST['full']));
However, when posting:
Hello
Hello
Hello
The script actually outputs:
HellornrnHellornrnHello..
jestep
Jul 31st 2007, 11:21 am
It looks like the stripslashes( is messing up your input.
Since a line break looks like a \r or \n, the strip slashes is removing the \ and you end up with a r or n. nl2br looks for the \n \r and cant find them so it doesn't do anything.
crazyryan
Jul 31st 2007, 11:24 am
Ohh, is there any way around that then?
jestep
Jul 31st 2007, 11:31 am
You could add the <br /> before you do anything else with that specific input.
cleanstring(nl2br($_POST['full']));
alhen
Jul 31st 2007, 11:55 am
worth telling you about though.
$test=$_POST['test'];
$test = preg_replace("/\n/","\n<BR>\n",$test);
I'm a newb and I'm sure lotsa people can poke holes in this, but there it is.
Also, I may be TOTALLY missing the point on this, but it seems like the answer to your question may have been complicated. the simple way to use nl2br would be similar to my above code:
$test=$_POST['test'];
$test = nl2br($test);
--
~alhen
toby
Jul 31st 2007, 12:03 pm
hehe, yes, use nl2br . php is great! remember to strip away the tag as well
feri_soft
Jul 31st 2007, 2:22 pm
Well i would suggest you using the nl2br after querying the database not putting in the <br /> 's in the database. This will be more flexible for you to just use the /n as its better supported in php than the html tag. However its your choice .
nagasharmi
Aug 2nd 2007, 1:48 am
echo '<br>'.$_POST['text'];
vBulletin® v3.6.8, Copyright ©2000-2008, Jelsoft Enterprises Ltd.