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>
Single quotes tell Integration Engine to take what is enclosed in the single quotes literally. No escaping is used with single quotes. Use a double backslash as the escape character for backslash.
The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one. The single quote is the escape character in Oracle, SQL Server, MySQL, and PostgreSQL.
Alternatively, you can use a backslash \ to escape the quotation marks.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With