如何只使用单引号?

时间:2022-09-15 15:34:42

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?

我正在编写一些JavaScript代码,其中使用了用PHP提供的字符串。如何在PHP字符串中转义单引号(且仅转义单引号)?

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

11 个解决方案

#1


49  

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

非常简单:echo str_replace('\ " \\\ \ " $myString);但是,我建议使用JSON和json_encode()函数,因为它更可靠(例如引用新行):

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

#2


16  

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

#3


9  

To replace only single quotes, use this simple statement:

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

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

#4


9  

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 HTML page, visual output is same:

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

ABC\DEFGH'IJKL

however,it is sanitized in source.

但是,它在源代码中是经过消毒的。

#5


8  

If you want to escape chars with a \you have addcslashes() for example if you want to escape only single quotes like the question you can do:

如果你想用一个\来转义chars,你有addcslash(),例如,如果你想转义像你可以做的这样的单引号:

echo addcslashes($value, "'");

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

如果你想转义,",\和nul(字节null)你可以使用addslashes():

echo addslashes($value);

#6


1  

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

在与这个问题进行了长时间的斗争之后,我认为找到了更好的解决办法。

Combine two functions make possible escape a string to use as HTML.

合并两个函数可以将字符串转义为HTML。

One to escape double quote if you use the string inside a javascript function call, andother to escape the single quote to avoid those simple quote that go around the argument.

一个是转义双引号,如果你在javascript函数调用中使用字符串,另一个是转义单引号,以避免在参数中出现简单的引号。

Solution:

解决方案:

mysql_real_escape_string(htmlspecialchars($string))

Solve:

解决:

  • a php created to call a javascript function like
  • 创建来调用javascript函数的php

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

回声的onclick = " javascript_function(\ " .mysql_real_escape_string(htmlspecialchars函数(字符串)美元)"

#7


1  

I know I am late to the party. But you can utilize addcslashes function to get this done like so,

我知道我参加聚会迟到了。但是你可以使用addcslashes函数来完成这个操作,

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

#8


0  

Not sure what exactly you are doing with your data, but you could always try:

不确定你到底在用你的数据做什么,但你可以尝试:

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

$ string =(“的”、“% 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 '.

当字符串被发送到数据库进行存储时,我就使用这个。%27是“字符”的编码,如果发送到服务器的字符串中包含单个“字符”,它还有助于防止GET请求中断。我将用%27替换javascript和PHP中的%27,以防有人试图手动向PHP函数发送数据。为了使最终用户更满意,只需对从服务器返回的所有数据运行反向替换函数,并将所有的%27子字符串替换为'。

Happy injection avoiding!

注入避免快乐!

#9


0  

I wrote the following function. It replaces the following:

我写了下面的函数。它取代以下:

Single Quote ['] with slash and 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".

您可以修改它以添加或删除$替换数组中的字符替换。例如,要替换\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. Example, "Cool\r\nFeature" will escape \r\n rather than escaping \n along.

strtr的优点是它更喜欢长替换。例如,“Cool\r\ nfeatures”将转义\r\n而不是转义\n。

#10


0  

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

我正在输出叫做JavaScript代码的HTML来显示图片……

#11


0  

Use native function htmlspecialchars it will escape from all special charector. if you want escape from quate specifically, use ENT_COMPAT or ENT_QUOTES. Here is the example.

使用本机函数htmlspecialchars它将从所有特殊的charector中转义。如果您特别想要从quate中转义,请使用ENT_COMPAT或ENT_QUOTES。这是例子。

$str = "Jane & 'Tarzan'";echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotesecho "<br>";echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotesecho "<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 here, https://www.w3schools.com/php/func_string_htmlspecialchars.asp

阅读更多在这里,https://www.w3schools.com/php/func_string_htmlspecialchars.asp

#1


49  

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

非常简单:echo str_replace('\ " \\\ \ " $myString);但是,我建议使用JSON和json_encode()函数,因为它更可靠(例如引用新行):

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

#2


16  

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

#3


9  

To replace only single quotes, use this simple statement:

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

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

#4


9  

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 HTML page, visual output is same:

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

ABC\DEFGH'IJKL

however,it is sanitized in source.

但是,它在源代码中是经过消毒的。

#5


8  

If you want to escape chars with a \you have addcslashes() for example if you want to escape only single quotes like the question you can do:

如果你想用一个\来转义chars,你有addcslash(),例如,如果你想转义像你可以做的这样的单引号:

echo addcslashes($value, "'");

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

如果你想转义,",\和nul(字节null)你可以使用addslashes():

echo addslashes($value);

#6


1  

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

在与这个问题进行了长时间的斗争之后,我认为找到了更好的解决办法。

Combine two functions make possible escape a string to use as HTML.

合并两个函数可以将字符串转义为HTML。

One to escape double quote if you use the string inside a javascript function call, andother to escape the single quote to avoid those simple quote that go around the argument.

一个是转义双引号,如果你在javascript函数调用中使用字符串,另一个是转义单引号,以避免在参数中出现简单的引号。

Solution:

解决方案:

mysql_real_escape_string(htmlspecialchars($string))

Solve:

解决:

  • a php created to call a javascript function like
  • 创建来调用javascript函数的php

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

回声的onclick = " javascript_function(\ " .mysql_real_escape_string(htmlspecialchars函数(字符串)美元)"

#7


1  

I know I am late to the party. But you can utilize addcslashes function to get this done like so,

我知道我参加聚会迟到了。但是你可以使用addcslashes函数来完成这个操作,

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

#8


0  

Not sure what exactly you are doing with your data, but you could always try:

不确定你到底在用你的数据做什么,但你可以尝试:

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

$ string =(“的”、“% 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 '.

当字符串被发送到数据库进行存储时,我就使用这个。%27是“字符”的编码,如果发送到服务器的字符串中包含单个“字符”,它还有助于防止GET请求中断。我将用%27替换javascript和PHP中的%27,以防有人试图手动向PHP函数发送数据。为了使最终用户更满意,只需对从服务器返回的所有数据运行反向替换函数,并将所有的%27子字符串替换为'。

Happy injection avoiding!

注入避免快乐!

#9


0  

I wrote the following function. It replaces the following:

我写了下面的函数。它取代以下:

Single Quote ['] with slash and 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".

您可以修改它以添加或删除$替换数组中的字符替换。例如,要替换\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. Example, "Cool\r\nFeature" will escape \r\n rather than escaping \n along.

strtr的优点是它更喜欢长替换。例如,“Cool\r\ nfeatures”将转义\r\n而不是转义\n。

#10


0  

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

我正在输出叫做JavaScript代码的HTML来显示图片……

#11


0  

Use native function htmlspecialchars it will escape from all special charector. if you want escape from quate specifically, use ENT_COMPAT or ENT_QUOTES. Here is the example.

使用本机函数htmlspecialchars它将从所有特殊的charector中转义。如果您特别想要从quate中转义,请使用ENT_COMPAT或ENT_QUOTES。这是例子。

$str = "Jane & 'Tarzan'";echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotesecho "<br>";echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotesecho "<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 here, https://www.w3schools.com/php/func_string_htmlspecialchars.asp

阅读更多在这里,https://www.w3schools.com/php/func_string_htmlspecialchars.asp