note 39171 deleted from function.nl2br by aidan
| From: | aidan@php.net | Date: | Sun, 10 Oct 2004 10:37:06 +0000 |
| Subject: | note 39171 deleted from function.nl2br by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-78273@lists.php.net to get a copy of this message | ||
Note Submitter: alexandre at dutra-cancado dot net
----
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!