Reputation: 18649
Someone just made a group on my site which has a description with \n\r
. The thing is that I already do this to the description text:
//Convert all urls to links
$group_description = preg_replace('#([\s|^])(www)#i', '$1http://$2', $group_description);
$pattern = '#((http|https|ftp|telnet|news|gopher|file|wais):\/\/[^\s]+)#i';
$replacement = '<a href="$1" target="_blank">$1</a>';
$group_description = preg_replace($pattern, $replacement, $group_description);
$group_description = str_replace("\'" , "'", $group_description );
$group_description = nl2br($group_description);
/* Convert all E-mail matches to appropriate HTML links */
$pattern = '#([0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.';
$pattern .= '[a-wyz][a-z](fo|g|l|m|mes|o|op|pa|ro|seum|t|u|v|z)?)#i';
$replacement = '<a href="mailto:\\1">\\1</a>';
$group_description = preg_replace($pattern, $replacement, $group_description);
You can see this happening here.
You see it says there \n\r Welcome to Join
.
Why didn't it become a <br />
tag?
This is probably important, here is how I put this text into the db in the first place:
$group_description = mysql_real_escape_string($_POST['group_description']);
// And then insert the $group_description into the db without doing any more operations on it.
Any idea why I am still getting the \n\r
?
Upvotes: 1
Views: 593
Reputation: 145512
You've answered it yourself. mysql_real_escape_string
also converts linebreaks into the escape sequences \r
and \n
.
You must apply your conversions first (including nl2br
) and do the database escaping/marshalling right before the mysql_query. (But you know, there are also much easier to use database APIs.)
Upvotes: 2
Reputation: 24989
The problem is that the \r and \n are stored in your database as "\" "r" and "\" "\n" respectively. They're not stored as a carriage return or new line character but the slash character followed by the letter. When you're calling nl2br()
, it's looking for the new line character, not the textual representation of it. Hopefully that makes sense.
You could use a regular expression (preg_replace
) or str_replace
to replace them. But the problem probably is caused by how the data is inserted in your database.
For instance:
$string = str_replace('\n', "\n", $string);
$string = str_replace('\r', "\r", $string);
You'll notice that I used single quotes for the first one and double for the second. When using single quotes, the "\r" and "\n" are stored as text, not the special characters. That could by why they're not stored properly in your database.
Upvotes: 6