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>
If you want to escape characters with a \
, you have addcslashes()
. For example, if you want to escape only single quotes like the question, you can do:
echo addcslashes($value, "'");
And if you want to escape '
, "
, \
, and nul
(the byte null), you can use addslashes()
:
echo addslashes($value);