开发者

nl2br not working on ical summary line feeds "\n"

开发者 https://www.devze.com 2023-03-06 21:40 出处:网络
I\'m collecting a summary of an ical event in PHP. The thing is, that the summary contains line breaks \\nand I want to replace them with <br> when inserting the events.

I'm collecting a summary of an ical event in PHP. The thing is, that the summary contains line breaks \nand I want to replace them with <br> when inserting the events.

In my PHPMyAdmin after escaping the ical summary I see the characters \n, but without escaping the ical summary I can't see the characters \n. However, without escaping I can see actual real line-breaks. I need to escape the ical summary to make my database safe. Using the nl2br function is not working in both cases? Why?

CODE:

//without escaping
$title = $vevent->getProperty('summary');//Object method which retrieves the summary of an event 
$title = nl2br($title);

//with escaping
$title开发者_如何学JAVA = mysql_real_escape_string($vevent->getProperty('summary'));
$title = nl2br($title);


Hrm, what about reading the handbook page, my friend? http://php.net/manual/en/function.mysql-real-escape-string.php says

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n,

Your line breaks are already SQL escaped. so you need to nl2br before.

And the usual rant I give to everyone: why are you using the mysql extension in 2011? It went out of fashion half a decade ago. Use mysqli or PDO and prepared statements, then you dont need to worry about escaping.


You can do it the other way around:

//with escaping
$title = nl2br($title);
$title = mysql_real_escape_string($vevent->getProperty('summary'));

But you shouldn't need to call nl2br before inserting into the database. It's better to do nl2br when you output the data to the browser. That way you store the actual data in the database (which later can be used in other context) and format it with HTML before outputting.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号