RE: [PHP] Escaping JavaScript strings
| From: | Edward Kay | Date: | Thu, 29 May 2008 12:23:40 +0000 |
| Subject: | RE: [PHP] Escaping JavaScript strings | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-274807@lists.php.net to get a copy of this message | ||
>
> This is a PHP function that escapes strings so you can output them as a
> JS string. IIRC it assumes you're using single quotes to enclose your
> strings.
>
> /**
> * Function to appropriately escape a string so it can be output
> * into javascript code.
> *
> * @param string $string Input string to escape
> * @return string Escaped string
> */
> function escapeString($string)
> {
> $js_escape = array("\r" => '\r',
> "\n" => '\n',
> "\t" => '\t',
> "'" => "\\'",
> '\\' => '\\\\');
>
> return strtr($string, $js_escape);
> }
Just what was needed - thanks Richard.
Edward