source

작은따옴표가 아닌 큰따옴표에만 슬래시를 추가하는 PHP 기능이 있습니까?

factcode 2023. 3. 5. 21:59
반응형

작은따옴표가 아닌 큰따옴표에만 슬래시를 추가하는 PHP 기능이 있습니까?

PHP로 JSON을 생성하고 있습니다.

사용하고 있습니다.

$string = 'This string has "double quotes"';

echo addslashes($string);

출력:This string has \" double quotes\"

완전히 유효한 JSON

유감스럽게도 애드슬래시는 유효한 JSON의 치명적인 결과를 나타내는 단일 따옴표도 제외됩니다.

$string = "This string has 'single quotes'";

echo addslashes($string);

출력:This string has \'single quotes\'

즉, 큰따옴표만 피할 수 있는 방법은 없는 것입니까?

사용 가능한 경우 를 사용해야 하지만 를 사용하여 다음을 추가할 수도 있습니다.\다음과 같은 특정 문자에만 해당됩니다.

addcslashes($str, '"\\/')

정규 표현식 기반의 치환을 사용할 수도 있습니다.

function json_string_encode($str) {
    $callback = function($match) {
        if ($match[0] === '\\') {
            return $match[0];
        } else {
            $printable = array('"' => '"', '\\' => '\\', "\b" => 'b', "\f" => 'f', "\n" => 'n', "\r" => 'r', "\t" => 't');
            return isset($printable[$match[0]])
                   ? '\\'.$printable[$match[0]]
                   : '\\u'.strtoupper(current(unpack('H*', mb_convert_encoding($match[0], 'UCS-2BE', 'UTF-8'))));
        }
    };
    return '"' . preg_replace_callback('/\\.|[^\x{20}-\x{21}\x{23}-\x{5B}\x{5D}-\x{10FFFF}/u', $callback, $str) . '"';
}

작은따옴표가 아닌 큰따옴표에만 슬래시를 추가하는 PHP 기능이 있습니까?

큰따옴표에 슬래시만 추가하는 기능은 없습니다.

단, 를 사용하여 슬래시를 추가할 수 있는 것은 특정 문자뿐입니다(: 큰따옴표).

addcslashes($string, '"');

그것은 정확히 설명된 대로 작동합니다.단, 호환성을 유지하려면 슬래시 자체를 문자 목록에 추가해야 합니다.

addcslashes($string, '"\\');

그 정도면 자네가 부탁했던 일이 될 거야.그것이 json 인코딩에 대응하고 있는지 알 수 없습니다.

JSON을 생성하는 경우 이 기능을 사용하면 어떨까요?

function json_string_encode( $str ) {
   $from = array('"');    // Array of values to replace
   $to = array('\\"');    // Array of values to replace with

   // Replace the string passed
   return str_replace( $from, $to, $str );
}

필요한 기능을 사용하기 위해서

$text = json_string_encode($text);

언급URL : https://stackoverflow.com/questions/5611468/is-there-a-php-function-that-only-adds-slashes-to-double-quotes-not-single-quote

반응형