How do I escape only single quotes?

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>

Leave a Comment