简体   繁体   中英

Convert PHP double quotes to single quotes

I'm creating a PHP class that can write an array of strings to a file, which is then read line-by-line.

I need to make sure that special characters like '\\n' get written to the file literally, rather than messing with the format of the file. This only seems to work when using single-quoted strings.

<?php
//EXAMPLE ONE - DOUBLE QUOTES ----------
$user_input = "This is the \n input.";
file_put_contents("input.txt", $user_input);
//OUTPUT
//
//This is the
// input.
//

//EXAMPLE TWO - SINGLE QUOTES ----------
$user_input = 'This is the \n input.';
file_put_contents("input.txt", $user_input);
//OUTPUT
//
//This is the \n input.
//
?>

How can I achieve the output of example two even if $user_input is in double quotes?

When using double quotes, the backslash \\ character enables special usage, eg \\n is a newline (within the text).

To get an actual backslash in your text use need to add two:

$user_input = "This is the \\n input.";

For more information on the backslash usages, check the documentation .

No! You can't do that.

From the manual :

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters.

You need to work on an alternate method like adding double slashes.

str_replace('\', '\\', $user_input);

This will escape all the special characters. Now, if there is double quotes, then it will be displayed, like the way you need.

Alternatively, you can do this way too... When printing the output, you can escape the special characters into their characters this way:

str_replace(array("\n", "\t"), array('\n', '\t'), $user_input);

It is happening because \\n is cosidering as new line charcter here, so you escape the character. change it to \\\\n

str_replace("\n","\\n", $user_input);

the right answer as follows:

$user_input = str_replace (array("\n","\r"), " ", $user_input);

it replaces newline characters with a space which seems most convenient replacement (but may be changed according to the future purpose of the string. Say, if you're going to print it in HTML, '<br>' would be better replacement)

though quotes has nothing to do with it. they are part of PHP syntax only, and don't have any special meaning in the user input

$user_input = "This is the \n input."

You have to use \\ for any special character. If you want to print text is 'abcd' here so you have to write \\'abcd\\' to print this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM