IT TIP

작은 따옴표 만 이스케이프하려면 어떻게합니까?

itqueen 2020. 11. 20. 17:29
반응형

작은 따옴표 만 이스케이프하려면 어떻게합니까?


PHP로 렌더링 된 문자열을 사용하는 JavaScript 코드를 작성 중입니다. PHP 문자열에서 작은 따옴표 (및 작은 따옴표 만)를 어떻게 이스케이프 할 수 있습니까?

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

간단히 말해서 : echo str_replace('\'', '\\\'', $myString);그러나 JSONjson_encode()함수를 사용하는 것이 더 안정적이므로 권장합니다 (예 : 새 줄 인용).

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

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

으로 문자를 이스케이프 \하려면 addcslashes(). 예를 들어 질문과 같이 작은 따옴표 만 이스케이프하려면 다음을 수행 할 수 있습니다.

echo addcslashes($value, "'");

탈출 싶다면 ', ", \, 및 nul(바이트 널 (null)), 당신은 사용할 수 있습니다 addslashes():

echo addslashes($value);

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

어떤 경우에는 ENTITIES로 변환합니다.

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

HTML 페이지에서 시각적 출력은 동일합니다.

ABC\DEFGH'IJKL

그러나 소스에서 살균됩니다.


작은 따옴표 만 바꾸려면 다음 간단한 문을 사용하십시오.

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

addcslashes 함수를 사용하여 다음과 같이 수행 할 수 있습니다 .

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

기본 함수를 사용합니다 htmlspecialchars. 모든 특수 문자에서 벗어날 것입니다. 특별히 견적에서 탈출하려면, 사용 ENT_COMPAT또는 ENT_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

출력은 다음과 같습니다.

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

PHP htmlspecialchars () 함수 에서 자세히 알아보기


이 문제와 오랜 시간 동안 싸운 끝에 더 나은 해결책을 찾은 것 같습니다.

두 함수를 결합하면 문자열을 이스케이프하여 HTML로 사용할 수 있습니다.

하나는 JavaScript 함수 호출 내에서 문자열을 사용하는 경우 큰 따옴표를 이스케이프하고 다른 하나는 인수를 둘러싼 단순한 따옴표를 피하기 위해 작은 따옴표를 이스케이프합니다.

해결책:

mysql_real_escape_string(htmlspecialchars($string))

풀다:

  • JavaScript 함수를 호출하기 위해 생성 된 PHP 라인

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


내가 한 방법은 다음과 같습니다. 어리석지 만 간단합니다.

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

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

그림을 보여주기 위해 JavaScript 코드를 호출하는 HTML을 출력하는 작업을하고있었습니다.


데이터로 정확히 무엇을하는지 잘 모르겠지만 항상 시도해 볼 수 있습니다.

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

저장을 위해 문자열이 데이터베이스로 전송 될 때마다 이것을 사용합니다.

% 27은 '문자의 인코딩이며 '서버로 전송 된 문자열에 단일 문자가 포함 된 경우 GET 요청 중단을 방지하는데도 도움이됩니다 . 누군가가 수동으로 PHP 함수에 데이터를 보내려고하는 경우를 대비하여 JavaScript와 PHP에서 '를 % 27로 대체합니다.

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!


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.

참고URL : https://stackoverflow.com/questions/6269188/how-do-i-escape-only-single-quotes

반응형