PHP将字符串“按原样”保存到文件中,包括例如

I have a variable which contains a string, I don't know what the string might be but it could contain special characters.

I'd like to output that into a text file "as is". So if there is for example a string "my string " I want the text file to show exactly that and not interpret the as a line feed / new line.

The answer for " " is to replace any potential new line character with the literal characters. str_replace(" ", ' ', $myString)

Not sure what the general case may be though for other potential special characters.

Then make sure it's "as is" in the string, e.g. "my string \ " or 'my string '. PHP is not doing any transformation on the actual data - the transformation of " " to a newline happens when PHP parses the string literal in code.

Now, assuming that you want an actual newline character (" ") in the data/string to be written as a sequence of two characters (' '), then it must be converted back, e.g.:

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

There are likely better (read: existing) functions to "de-escape" a string per a given set of rules, but the above should hopefully show the concepts.


While everything above is true/valid (or should be corrected if not), I had a little extra time on my hands to create an escape_as_double_quoted_literal function.

Given an "ASCII encoded" string $str and $escaped = escape_as_double_quoted_literal($str), it should be the case that eval("\"$escaped\"") == $str. I'm not exactly sure when this particular function will be useful (and please don't say for eval!), but since I did not find such a function after some immediate searches, this is my quick implementation of such. YMMV.

function escape_as_double_quoted_literal_matcher ($m) {
    $ch = $m[0];
    switch ($ch) {
        case "
": return '
';
        case "": return '';
        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);
}

And the usage of such:

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

(Note that '\1' is encoded as \x01; both are equivalent in a PHP double-quoted string literal.)