How do I escape only single quotes?
escaping, php
Solution
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):
<?php $data = array('myString' => '...'); ?>
<script>
var phpData = <?php echo json_encode($data) ?>;
alert(phpData.myString);
</script>
Problem
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> ```