PHP将字符串保存到文件“;“照原样”;包括例如


PHP saving a string to a file "as is" including eg

我有一个包含字符串的变量,我不知道字符串可能是什么,但它可能包含特殊字符。

我想把它按原样输出到一个文本文件中。因此,例如,如果有一个字符串"my string",我希望文本文件准确地显示这一点,而不是将其解释为换行符/新行。

然后确保它在字符串中"原样",例如"my string ''n"'my string 'n'。PHP没有对实际数据进行任何转换-当PHP解析代码中的字符串文字时,"'n"到换行符的转换发生在

现在,假设您希望数据/字符串中的实际换行符("'n"(被写为两个字符的序列(''n'(,则必须将其转换回,例如:

# 'n is converted to a NL due to double-quoted literal ..
$strWithNl = "hello'n world";
# but given arbitrary data, we change it back ..
$strWithSlashN = str_replace("'n", ''n', $strWithNl);

可能有更好的(读作:现有的(函数可以根据给定的规则集"取消转义"字符串,但以上应该有望展示这些概念。


虽然上面的所有内容都是正确/有效的(如果不是,则应该更正(,但我有一点额外的时间来创建escape_as_double_quoted_literal函数。

给定一个"ASCII编码"的字符串$str$escaped = escape_as_double_quoted_literal($str),应该是eval("'"$escaped'"") == $str的情况。我不确定这个特定的函数什么时候会有用(请不要说eval!(,但由于我在一些即时搜索后没有找到这样的函数,这是我快速实现的YMMV

function escape_as_double_quoted_literal_matcher ($m) {
    $ch = $m[0];
    switch ($ch) {
        case "'n": return ''n';
        case "'r": return ''r';
        case "'t": return ''t';
        case "'v": return ''v';
        case "'e": return ''e';
        case "'f": return ''f';
        case "''": return '''''';
        case "'$": return ''$';
        case "'"": return '''"';
        case "'0": return ''0';
        default:
            $h = dechex(ord($ch));
            return ''x' . (strlen($h) > 1 ? $h : '0' . $h);
    }
}
function escape_as_double_quoted_literal ($val) {
    return preg_replace_callback(
            "|[^'x20'x21'x23'x25-'x5b'x5e-'x7e]|",
            "escape_as_double_quoted_literal_matcher",
            $val);
}

以及这样的用法:

$text = "'0'1'xff'"hello''world'"'n'$";
echo escape_as_double_quoted_literal($text);

(请注意,''1'编码为'x01;两者在PHP双引号字符串文字中是等效的。(

"''n"的答案是用文字字符替换任何潜在的换行符。str_replace("'n", ''n', $myString)

不确定其他潜在特殊角色的一般情况。