Escaping escape Characters

前端 未结 6 1291
悲哀的现实
悲哀的现实 2020-12-31 17:41

I\'m trying to mimic the json_encode bitmask flags implemented in PHP 5.3.0, here is the string I have:

$s = addslashes(\'O\\\'Rei\"lly\'); // O         


        
6条回答
  •  死守一世寂寞
    2020-12-31 18:05

    When you encode a string for json, some things have to be escaped regardless of the options. As others have pointed out, that includes '\' so any backslash run through json_encode will be doubled. Since you are first running your string through addslashes, which also adds backslashes to quotes, you are adding a lot of extra backslashes. The following function will emulate how json_encode would encode a string. If the string has already had backslashes added, they will be doubled.

    function json_encode_string( $encode , $options ) {
        $escape = '\\\0..\37';
        $needle = array();
        $replace = array();
    
        if ( $options & JSON_HEX_APOS ) {
            $needle[] = "'";
            $replace[] = '\u0027';
        } else {
            $escape .= "'";
        }
    
        if ( $options & JSON_HEX_QUOT ) {
            $needle[] = '"';
            $replace[] = '\u0022';
        } else {
            $escape .= '"';
        }
    
        if ( $options & JSON_HEX_AMP ) {
            $needle[] = '&';
            $replace[] = '\u0026';
        }
    
        if ( $options & JSON_HEX_TAG ) {
            $needle[] = '<';
            $needle[] = '>';
            $replace[] = '\u003C';
            $replace[] = '\u003E';
        }
    
        $encode = addcslashes( $encode , $escape );
        $encode = str_replace( $needle , $replace , $encode );
    
        return $encode;
    }
    

提交回复
热议问题