The difference between PHP single and double quotes _php tips

Source: Internet
Author: User
Tags php code
1. Define String   

In PHP, a string can be defined using single quotes or double quotes. However, you must use the same single or double quotes to define the string, such as: ' Hello ' and ' hello ' are illegal string definitions.
When you define a string, only one quotation mark is treated as a definition character, either single or double quotes. So, if a string starts with double quotes, then only double quotes are parsed by the parser. This way, you can include any other character, even single quotes, in the double quote string. The following quotation marks are valid:
PHP code
Copy Code code as follows:

$s = "I am a ' single quote string ' inside a double quote string";
$s = ' I am ' a ' double quote string ' inside a single quote string ';
$s = "I am a ' single quote string ' inside a double quote string";
$s = ' I am ' a ' double quote string ' inside a single quote string ';

And the string "Why doesn ' t" this "work" will be divided into three paragraphs. If you want to represent double quotes in this string, you can use the escape character "\" (backslash) to change to "Why doesn" this\ "work?".

2. Single and double quotes in string variables  
 
PHP allows us to include string variables directly in a double quote string, and we can see that the following two strings have the same processing results.
Copy Code code as follows:

$full _name = $first _name. ' ' . $last _name;
$full _name = "$first _name $last _name";

Single quote strings and double quote strings are handled differently in PHP. The contents of a double quote string can be interpreted and replaced, and the contents of a single quote string are always considered normal characters. For example:
PHP code
Copy Code code as follows:

$foo = 2;
echo "Foo is $foo"; Printed Result: Foo is 2
Echo ' foo is $foo '; Printed result: Foo is $foo
echo "Foo is $foo \ n"; Printed Result: Foo is 2 (newline at the same time)
Echo ' foo is $foo \ n '; Printed result: Foo is $foo \ n
$foo = 2;
echo "Foo is $foo"; Printed Result: Foo is 2
Echo ' foo is $foo '; Printed result: Foo is $foo
echo "Foo is $foo \ n"; Printed Result: Foo is 2 (newline at the same time)
Echo ' foo is $foo \ n '; Printed result: Foo is $foo \ n

As you can see, even the backslash in the single quote string loses his extended meaning (except inserting a backslash \ and inserting single quotes \). So, you should use double quotes when you want to make variable substitutions in a string and include the escape sequences of \ n (line breaks). Single quote strings can be used anywhere else, and the use of single quote strings in a script is faster because the PHP parser handles single quote strings in a simpler way, and double quotes are more complex because they need to be parsed inside the string, so the processing speed is slightly slower.
When you refer to a complex combination of variables in a string, some problems may arise and the following code works correctly:
PHP code
Copy Code code as follows:

echo "value = $foo";
echo "value = $a [$i]";
echo "value = $foo";
echo "value = $a [$i]";

The following code does not get the result we want:
echo "value = $a [$i] [$j]"; We want to print an element of the two-dimensional array $a.
To avoid potential problems with these strings, we usually separate complex variables from strings, like this: echo ' value = '. $a [$i] [$j The connection of the];//string with dots (.)
Another option is to enclose complex variables in curly braces, and the parser can correctly identify:
echo "value = {$a [$i] [$j]}"//print an element of a two-dimensional array $a
In this way, there are new problems. When we want to refer to the curly braces character itself in a string, remember to use the escape character:
PHP code
Copy Code code as follows:

$var = 3;
echo "value = {$var}"; Print result "value = 3"
echo "value = \{$var}"; Print Result "value = {3}"
$var = 3;
echo "value = {$var}"; Print result "value = 3"
echo "value = \{$var}"; Print Result "value = {3}"


3, in the SQL statement  
 
This is a recurring problem, when the SQL statement that inserts the database uses single quotes to define the string, and if you insert a string that contains single quotes into the database, the SQL statement will go wrong.
such as: $sql = "INSERT into UserInfo (Username,password) Values (' O ' kefee ', ' 123456 ')"
At this point, one of the ways to handle this is to add an escape character backslash to the SQL statement.
That is: ... Values (' o\ ' Kefee ',......
Of course, you can also use the function addslashes (), the function of which is to add an escape character,
namely: $s = addslashes ("O ' Kefee") ... Values (' ". $s." ',......
There is also a way to set the Magic-quotes option in PHP.ini, which opens the option so that if a single quote is in the information submitted by the form, it will automatically be added as an escape character. So you don't have to use other functions.
Add: This is going to start with double quotes and single quotes: The fields inside the double quotes are interpreted by the compiler and then exported as HTML code, but the single quote doesn't need to be interpreted and directly output.
For example:
Copy Code code as follows:

$ABC = ' I love u ';
echo $ABC//Result: I love u
The echo ' $abc '//result is: $ABC
echo "$ABC"//Result: I love u

So when you assign a value to a SQL statement inside a database, you also use double quotes inside sql= "Select A,b,c from ..." But there's a single quote in the SQL statement that leads to the field name.
For example: SELECT * FROM table where user= ' abc ';
The SQL statement here can be written directly into the sql= "select * from table where user= ' abc '"
But if it's like the following:
Copy Code code as follows:

$user = ' abc ';
Sql1= "SELECT * from table where user= '". $user. " "; contrast
Sql2= "SELECT * from table where user= ' abc '"

I've added a little space between the single and double quotes, and I hope you can see it clearly.
Which is to replace ' abc ' with '. $user. ' It's all in one single quote. Just split the entire SQL string. SQL1 can be decomposed into the following 3 parts
1: "SELECT * from table where user= '"
2: $user
3: "'"
Used between strings. To connect, so you can understand.

A. Quote definition string

In PHP, a string is usually defined in a pair of quotes, such as:
' I am a string in single quotes '
"I am a string in double quotes"
The PHP parser uses a pair of quotes to judge a string. Therefore, all strings must use the same single or double
Quotation marks to define the start and end. For example, the following definition of a string is not valid:
"I am not a valid string since I have unmatching quote marks '"
' Me neither! '
When you define a string, only one quotation mark is treated as a definition character, either single or double quotes. So if a string is doubly cited
Start, then only double quotes are parsed by the parser. This way, you can include any other character in the double quote string, or even a single citation
Resolution The following quotation marks are valid:
$s = "I am a ' single quote string ' inside a double quote string";
$s = ' I am ' a ' double quote string ' inside a single quote string ';
When PHP encounters the quotation marks that correspond to the beginning of the string, it is considered to be at the end of the string, so:
"Why doesn ' t" this "work?"
is actually divided into three parts by the PHP parser:
"Why doesn ' t"--a double quote string containing a single quote
this--extra characters, analyzer cannot handle
"Work?"--normal string
The above example attempts to include double quotes in a double quote string, and the parser finds the string knot when it encounters the second double quote
Bunch up. To achieve the purpose of including quotation marks, the parser must ignore its original meaning when it encounters a string of ordinary quotes, and we
Precede with a backslash to tell PHP: This quotation mark is part of the string, and the correct notation is this:
"Why doesn ' t" that\ "work?"
A common problem in the English string is the use of apostrophes because it is a single quote, which is very common in English strings.
(All lattices in English). You have to be careful with these characters:
' You\ ' d better escape your apostrophes '
You can see that the backslash has a special meaning in the string, and when we need to include the backslash itself in the string, we need to
The symbol is preceded by an extra backslash. For example:
$file = "C:\Windows\System.ini";
Echo $file; Print Result: C:windowssystem.ini
$file = "C:\\windows\\system.ini";
Echo $file; Print Result: C:\Windows\System.ini
Another way to define a string is to eliminate the annoyance of special characters and to make it easier to refer to longer text. The string defines the square
The method begins with the <<< symbol immediately after a custom string, the last line ends with that custom string, and must be below.

Second, the string connection

Strings can be used with string connectors (.) To connect, such as:
$first _name = ' Charlie ';
$last _name = ' Brown ';
$full _name = $first _name. ' ' . $last _name;
A common use is to create large chunks of HTML string code, and the assignment number (=) connector (.) can be combined with the (. =) character by shorthand.
Number, such as:
$html = ' <table> ';
$html. = ' <tr><td>number</td><td>square</td></tr> ';
for ($i =0; $i <10; $i + +) {
$square = $i * $i;
$html. = ' <tr><td> '. $i. ' </td><td> '. $square. ' </td></tr> ';
}
$html. = ' </table> ';

iii. using variables in strings

This feature allows you to stick to a lot of simple strings without using a connection symbol. PHP allows us to include words directly in double quote strings
String variables, we can see that the following two string processing results are the same.
$full _name = $first _name. ' ' . $last _name;
$full _name = "$first _name $last _name";
Single quote strings and double quote strings are handled differently in PHP. The contents of a double quote string can be interpreted and replaced, and the single citation
The contents of the serial number are always considered to be ordinary characters. For example:
$foo = 2;
echo "Foo is $foo"; Printed Result: Foo is 2
Echo ' foo is $foo '; Printed result: Foo is $foo
echo "Foo is $foo \ n"; Printed Result: Foo is 2 (newline at the same time)
Echo ' foo is $foo \ n '; Printed result: Foo is $foo \ n
As you can see, even a backslash in a single quote string loses his extended meaning (except inserting a backslash \ \ and inserting a single
Quotes \ '). So, when you want to make a variable substitution in a string and an escape sequence that contains \ n (line breaks), you should use a double citation
Resolution Single quote strings can be used anywhere else, and the use of single quotes in a script can be faster because the PHP parser
Single quote string processing is relatively simple, and the processing of double quotes because the string inside also need to parse, so more complex, so the processing speed
Slightly slower.
When you refer to a complex combination of variables in a string, some problems may arise and the following code works correctly:
echo "value = $foo";
echo "value = $a [$i]";
The following code does not get the result we want:
echo "value = $a [$i] [$j]"; We want to print an element of the two-dimensional array $a.
To avoid potential problems with these strings, we usually separate complex variables from strings, like this:
echo ' value = '. $a [$i] [$j];
Another option is to enclose complex variables in curly braces, and the parser can correctly identify:
echo "value = {$a [$i] [$j]}"//print an element of a two-dimensional array $a
In this way, there are new problems. When we want to refer to the curly braces character itself in a string, remember to use the escape character:
$var = 3;
echo "value = {$var}"; Print result "value = 3"
echo "value = \{$var}"; Print Result "value = {3}"

three, Slash and SQL statements

Generating HTML code or SQL query statements is often an interesting thing to do when writing PHP programs. Why do you say that,
Because this involves generating another type of code, you must carefully consider and follow the writing syntax and rules required by this Code
The
Let's take a look at an example where you want to query a user whose name is "O ' Keefe" in the database, usually in the form of a SQL statement
That is true:
SELECT * from users where last_name = ' o\ ' Keefe '
Note that all the cells in the SQL statement (apostrophes) need to be escaped with a backslash. PHP specifically provides a number of functions to handle this
, the purpose of function addslashes ($STR) is to automatically insert the backslash escape character into a string:
$last _name = "O ' Keefe";
$sql = "SELECT * from users where last_name = '". Addslashes ($last _name). "'";
In this example, you also enclose a single quotation mark outside the last_name string (SQL syntax requirements), because it uses a double
Quotation marks, so the single quotation marks do not need to be escaped with. The following statement is the equivalent of using a single quote string:
$sql = ' SELECT * from users where last_name = \ '. Addslashes ($last _name). '\'';
Any time you want to write a string in a database, you have to make sure that the quotes inside are correctly using the escape symbol, which is a lot of PHP
Mistakes that beginners often make.

four, double quotes and HTML

Unlike SQL statements, double quotes are often used to represent strings in standard HTML languages (many browsers now have strong fault-tolerant work
To allow the use of single quotes or even quotes to denote strings in HTML, for example:
$html = ' <a href= '. $url. ' " > '. $link. ' </a> ';
$html = "<a href=\" $url \ "> $link </a>";
The HTML language does not support backslash escaping, which is when we use the hidden inputs of the form to transmit data
Feel it. The best way to set the value of hidden inputs is to use the Htmlspecialchars () function to encode it. The following statement can be
To normally transmit a data that may contain double quotes:
<input type=hidden name=var value= "<?php Echo htmlspecialchars ($var)?>" >

A, quotation mark defines a string. To achieve the purpose of including quotes, it is necessary for the parser to ignore its original meaning when it encounters a string of ordinary quotes, and we add a backslash to the front of the quotation mark to tell PHP: The quotation mark is part of the string, and the correct representation is this: single quote string can be used anywhere else, Using a single quote string in a script can be faster because the PHP parser handles the single quote string more simply, and the double quotes are more complex because they need to be parsed inside the string, so the processing speed is slightly slower.

This one... Double quotes Escape, single quotes not escaping
For example:/r/n is a newline, but if you write the file in single quotes, it will not be a newline, but a character, if you write the file in double quotes, it is a newline.
Agree.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.