Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape only single quotes?

Tags:

php

escaping

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> 
like image 477
Andrew Avatar asked Jun 07 '11 17:06

Andrew


People also ask

How do you bypass a single quote?

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.

How do you escape a single quote in SQL?

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.

How do you escape quotation marks?

Alternatively, you can use a backslash \ to escape the quotation marks.


2 Answers

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> 
like image 152
Crozin Avatar answered Sep 20 '22 15:09

Crozin


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); 
like image 43
PhoneixS Avatar answered Sep 19 '22 15:09

PhoneixS