php 如何仅转义单引号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6269188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:50:43  来源:igfitidea点击:

How do I escape only single quotes?

phpescaping

提问by Andrew

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?

我正在编写一些使用 PHP 呈现的字符串的 JavaScript 代码。如何在我的 PHP 字符串中转义单引号(并且只有单引号)?

<script type="text/javascript">
    $('#myElement').html('say hello to <?php echo $mystringWithSingleQuotes ?>');
</script>

采纳答案by Crozin

Quite simply: echo str_replace('\'', '\\\'', $myString);However, I'd suggest use of JSONand json_encode()function as it will be more reliable (quotes new lines for instance):

很简单:echo str_replace('\'', '\\\'', $myString);但是,我建议使用JSONjson_encode()函数,因为它会更可靠(例如引用新行):

<?php $data = array('myString' => '...'); ?>

<script>
   var phpData = <?php echo json_encode($data) ?>;
   alert(phpData.myString);
</script>

回答by PhoneixS

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:

如果你想用 转义字符\,你有addcslashes(). 例如,如果您只想像问题一样转义单引号,则可以执行以下操作:

echo addcslashes($value, "'");

And if you want to escape ', ", \, and nul(the byte null), you can use addslashes():

如果你想转义', ", \, and nul(the byte null),你可以使用addslashes()

echo addslashes($value);

回答by Julian

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

回答by T.Todua

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:

在 HTML 页面上,视觉输出是相同的:

ABC\DEFGH'IJKL

However, it is sanitized in source.

但是,它在源头上已经过消毒。

回答by DevelRoot

To replace only single quotes, use this simple statement:

要仅替换单引号,请使用以下简单语句:

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

回答by Nishad Up

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

使用本机功能htmlspecialchars。它将摆脱所有特殊字符。如果您想专门从引用中转义,请使用 withENT_COMPATENT_QUOTES。这是示例:

$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

PHP htmlspecialchars() 函数中阅读更多内容

回答by Junior

You can use the addcslashesfunction to get this done like so:

您可以使用addcslashes函数来完成此操作,如下所示:

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

回答by arturocu81

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.

两个函数的组合使得转义字符串以用作 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.

一,如果您在 JavaScript 函数调用中使用字符串,则转义双引号;和第二个转义单引号,避免那些绕过参数的简单引号。

Solution:

解决方案:

mysql_real_escape_string(htmlspecialchars($string))

Solve:

解决:

  • a PHP line created to call a JavaScript function like
  • 创建用于调用 JavaScript 函数的 PHP 行,例如

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

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

回答by Basil Musa

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".

您可以修改它以在 $replacements 数组中添加或删除字符替换。例如,要替换 \r\n,它变成 "\r\n" => "\r\n" 和 "\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.

strtr 的巧妙之处在于它更喜欢长替换。

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

例如,“Cool\r\nFeature”将转义 \r\n 而不是转义 \n。

回答by Mike

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.

%27 是 ' 字符的编码,如果'发送到服务器的字符串中包含单个字符,它还有助于防止 GET 请求中断。我会在 JavaScript 和 PHP 中将 ' 替换为 %27,以防有人尝试手动向您的 PHP 函数发送一些数据。

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 '.

为了让您的最终用户更漂亮,只需为您从服务器返回的所有数据运行反向替换函数,并将所有 %27 子字符串替换为'.

Happy injection avoiding!

快乐注射避免!