How do I escape only single quotes?

PhpEscaping

Php Problem Overview


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>

Php Solutions


Solution 1 - Php

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>

Solution 2 - Php

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);

Solution 3 - Php

str_replace("'", "\'", $mystringWithSingleQuotes);

Solution 4 - Php

In some cases, I just convert it into ENTITIES:

                        // i.e.,  $x= ABC\DEFGH'IJKL
$x = str_ireplace("'",  "&apos;", $x);
$x = str_ireplace("\\", "&bsol;", $x);
$x = str_ireplace('"',  "&quot;", $x);

On the HTML page, the visual output is the same:

ABC\DEFGH'IJKL

However, it is sanitized in source.

Solution 5 - Php

Use the native function htmlspecialchars. It will escape from all special character. If you want to escape from a quote specifically, use with ENT_COMPAT or ENT_QUOTES. Here is the example:

$str = "Jane & 'Tarzan'";
echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotes
echo "<br>";

echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes
echo "<br>";

echo htmlspecialchars($str, ENT_NOQUOTES); // Does not convert any quotes

The output would be like this:

Jane &amp; 'Tarzan'<br>
Jane &amp; &#039;Tarzan&#039;<br>
Jane &amp; 'Tarzan'

Read more in PHP htmlspecialchars() Function

Solution 6 - Php

To replace only single quotes, use this simple statement:

$string = str_replace("'", "\\'", $string);

Solution 7 - Php

You can use the addcslashes function to get this done like so:

echo addcslashes($text, "'\\");

Solution 8 - Php

After a long time fighting with this problem, I think I have found a better solution.

The combination of two functions makes it possible to escape a string to use as HTML.

One, to escape double quote if you use the string inside a JavaScript function call; and a second one to escape the single quote, avoiding those simple quotes that go around the argument.

Solution:

mysql_real_escape_string(htmlspecialchars($string))

Solve:

  • a PHP line created to call a JavaScript function like

> echo > 'onclick="javascript_function('' . mysql_real_escape_string(htmlspecialchars($string))"

Solution 9 - Php

I wrote the following function. It replaces the following:

Single quote ['] with a slash and a single quote ['].

Backslash [\] with two backslashes [\\]

function escapePhpString($target) {
    $replacements = array(
            "'" => '\\\'',
            "\\" => '\\\\'
    );
    return strtr($target, $replacements);
}

You can modify it to add or remove character replacements in the $replacements array. For example, to replace \r\n, it becomes "\r\n" => "\r\n" and "\n" => "\n".

/**
 * With new line replacements too
 */
function escapePhpString($target) {
    $replacements = array(
            "'" => '\\\'',
            "\\" => '\\\\',
            "\r\n" => "\\r\\n",
            "\n" => "\\n"
    );
    return strtr($target, $replacements);
}

The neat feature about strtr is that it will prefer long replacements.

Example, "Cool\r\nFeature" will escape \r\n rather than escaping \n along.

Solution 10 - Php

I am not sure what exactly you are doing with your data, but you could always try:

$string = str_replace("'", "%27", $string);

I use this whenever strings are sent to a database for storage.

%27 is the encoding for the ' character, and it also helps to prevent disruption of GET requests if a single ' character is contained in a string sent to your server. I would replace ' with %27 in both JavaScript and PHP just in case someone tries to manually send some data to your PHP function.

To make it prettier to your end user, just run an inverse replace function for all data you get back from your server and replace all %27 substrings with '.

Happy injection avoiding!

Solution 11 - Php

Here is how I did it. Silly, but simple.

$singlequote = "'";
$picturefile = getProductPicture($id);

echo showPicture('.$singlequote.$picturefile.$singlequote.');

I was working on outputting HTML that called JavaScript code to show a picture...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrewView Question on Stackoverflow
Solution 1 - PhpCrozinView Answer on Stackoverflow
Solution 2 - PhpPhoneixSView Answer on Stackoverflow
Solution 3 - PhpJulianView Answer on Stackoverflow
Solution 4 - PhpT.ToduaView Answer on Stackoverflow
Solution 5 - PhpNishad UpView Answer on Stackoverflow
Solution 6 - Phpuser562854View Answer on Stackoverflow
Solution 7 - PhpJuniorView Answer on Stackoverflow
Solution 8 - Phparturocu81View Answer on Stackoverflow
Solution 9 - PhpBasil MusaView Answer on Stackoverflow
Solution 10 - PhpMikeView Answer on Stackoverflow
Solution 11 - PhpPaisano CentobieView Answer on Stackoverflow