Search code examples
phpjavascriptapostrophe

Apostrophe and Javascript / PHP


Right now I have this for my javascript code

'title': '<?=$name?>',

The thing is, occasionally $name will have an apostrophe in it, and can have the code look something like this

'title': 'Bon Jovi It's My Life - Bon Jovi',

which essentially screws up the javascript.

Would I just do a mysql_real_escape_string on the $name? Wouldn't that leave slashes in the title when I go to use it?

Thanks


Solution

  • <script type="text/javascript">
        var myJson = {
           title: '<?php echo addslashes($somePHPVar) ?>'
        };
    </script>
    

    addslashes is the key. See the docs.