I am writing some JavaScript code that uses a string rendered with PHP. How can I escape single quotes (and only single quotes) in my PHP string?
<script type="text/javascript">
$('#myElement').html('say hello to <?php echo $mystringWithSingleQuotes ?>');
</script>
Quite simply:
echo str_replace('\'', '\\\'', $myString);However, I’d suggest use of JSON and
json_encode()function as it will be more reliable (quotes new lines for instance):