NYCPHP Meetup

NYPHP.org

[nycphp-talk] What's the best way to escape JavaScript data?

Cliff Hirsch cliff at pinestream.com
Tue Jul 10 14:14:23 EDT 2007


What is the best way to escape JavaScript data?

The PEAR JavaScript package does this:

 function escapeString($str)  {
        $js_escape = array(
            "\r"    => '\r',
            "\n"    => '\n',
            "\t"    => '\t',
            "'"     => "\\'",
            '"'     => '\"',
            '\\' => '\\\\'
        );
        return strtr($str,$js_escape);
    }

I also found this, which converts every character to its code ‹ pretty
extreme.

function javascript_escape($str) {
    $new_str = '';
    for($i = 0; $i < strlen($str); $i++) {
        $new_str .= '\x' . dechex(ord(substr($str, $i, 1)));
    }
    return $new_str;
}

Thoughts?

Cliff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.nyphp.org/pipermail/talk/attachments/20070710/5af82ee5/attachment.html>


More information about the talk mailing list