note 39171 added to function.nl2br

From: Date: Mon, 19 Jan 2004 18:16:37 +0000
Subject: note 39171 added to function.nl2br
Groups: php.notes 
Request: Send a blank email to php-notes+get-63839@lists.php.net to get a copy of this message
Sometimes you need to write a PHP string in your source code so that it becomes the content of a javascript variable. Of course, LFs and CRs would result in real line breaks in your code, and JS cannot accept multi-line strings. Here's how to replace LFs and CRs in your PHP string by sequences that JS can accept and correctly handle (namely "\n" and "\r"): ========================= <?php $php_string ='Bonjour'.chr(9).'tout'.chr(13).'le'.chr(10).'monde!'; $js_string = preg_replace( '/([\r\n])/e', "ord('$1')==10?'\\n':'\\r'", $php_string ); ?> <script language="JavaScript" type="text/JavaScript"> //The following line contains a syntax error //and will not be displayed. alert('<?php echo $php_string;?>'); </script> <script language="JavaScript" type="text/JavaScript"> //The following line will be correctly displayed. alert('<?php echo $js_string;?>'); </script> ======================= Here's the resulting code: ======================= <script language="JavaScript" type="text/JavaScript"> //The following line contains a syntax error //and will not be displayed. alert('Bonjour tout le monde!'); </script> <script language="JavaScript" type="text/JavaScript"> //The following line will be correctly displayed. alert('Bonjour tout\rle\nmonde!'); </script> ======================== By the way, you should also be careful with quotes in your string, and another good idea is to use htmlspecialchars or htmlentities before writing it in your page. Hope this helps! ---- Manual Page -- http://www.php.net/manual/en/function.nl2br.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+39171 Delete -- http://master.php.net/manage/user-notes.php?action=delete+39171&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+39171&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#63839) next »