The difference between PHP single and double quotes

Source: Internet
Author: User

Original address: http://wenku.baidu.com/view/3e6a238271fe910ef12df806


"The distinction and usage of single and double quotes." Now the answer is summed up, written in this small essay.

The fields inside the double quotes are interpreted by the compiler and then exported as HTML code.


' Single quotes inside without explanation, direct output.


For example:
$ABC = ' My name is tome ';
echo $ABC//Result: My name is Tom
The echo ' $abc '//result is: $ABC
echo "$ABC"//Result: My name is Tom


Especially when using MySQL statements, the use of double quotes and single quotes makes the novice overwhelmed, here, for example, to illustrate.


Suppose a constant is used in a query condition, for example:


SELECT * from abc_table where user_name= ' abc ';


The SQL statement can be written as:


SQLSTR = "SELECT * from abc_table where user _name= ' abc '";


Suppose a variable is used in a query condition, for example:


$user _name = $_request[' user_name ']; String variables


Or


$user =array ("name" => $_request[' user_name ', "age" =>$_request[' age '];//array variable


The SQL statement can be written as:


SQLSTR = "SELECT * from abc_table where user_name = '". $user _name. " ' ";


SQLSTR = "SELECT * from abc_table where user_name = '". $user [' name ']. " ' ";


Compare:


Sqlstr= "SELECT * from abc_table where user_name = ' abc '";


Sqlstr= "SELECT * from abc_table where user_name = '". $user _name. " ' ";


Sqlstr= "SELECT * from abc_table where user_name = '". $user [' name ']. " ' ";


SQLSTR can be broken down into the following 3 sections:
1: "SELECT * FROM table where user_name = '"//fixed SQL statement
2: $user//variable
3: "'"
1,2,3 partial strings are connected by "."




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)?>" >




People often ask me, I heard that in PHP processing strings in single quotes will be faster, if there is a variable substitution, is the use of single quotes to connect faster, or double quotes fast. The simple answer is clearly feeble. Let's do an experiment today to see what the difference between single and double quotes is, who is fast and who is slow.


The test code is as follows:


<?php
$single _quotes = ' This is a String ';
$double _quotes = "This is a String";
echo $single _quotes;
echo $double _quotes;


$var = ' String ';
$single _quotes_var = ' This is a '. $var;
$double _quotes_var = "This is a $var";


echo $single _quotes_var;
echo $double _quotes_var;


$var = ' this ';


$single _quotes_var_pre = $var. ' is a String ';
$double _quotes_var_pre = "$var is a String";


echo $single _quotes_var_pre;
echo $double _quotes_var_pre;
?>
Next, let's take a look at the opcodes generator we mentioned in our previous article to see how our code was executed in the end:


Branch analysis from position:0
return found
FileName:/home/xinchen/string.php
Function name: (NULL)
Number of ops:24
Compiled VARs:!0 = $single _quotes,! 1 = $double _quotes,!2 = $var,!3 = $single _quotes_var,! 4 = $double _quotes_var,!5 = $single _quotes_var_pre,!6 = $double _quotes_var_pre
Line # OP fetch ext. operands
-------------------------------------------------------------------------------
2 0 ASSIGN! 0, ' this+is+a+string '
3 1 ASSIGN! 1, ' this+is+a+string '
4 2 ECHO!0
5 3 ECHO!1
7 4 ASSIGN! 2, ' String '
8 5 CONCAT ~3 ' this+is+a+ ',!2
6 ASSIGN! 3, ~3
9 7 init_string ~5
8 add_string ~5 ~5, ' this+is+a+ '
9 Add_var ~5 ~5,!2
Ten ASSIGN! 4, ~5
One by one ECHO!3
ECHO! 4
ASSIGN! 2, ' this '
CONCAT ~8! 2, ' +is+a+string '
ASSIGN 5, ~8
Init_string ~10
Add_var ~10 ~10,!2
Add_string ~10 ~10, ' +is+a+string '
ASSIGN! 6, ~10
ECHO!5
ECHO!6
Return 1
23* zend_handle_exception
Note that the No. 0 to 3rd op line shows that double quotes are the same as the opcodes generated by single quotes without using variable substitution.
Again: 4th to 12th, you can find that, in the case of variable substitution, using double quotes and single quotes generated by the opcodes is not the same, we analyze double quotes in the case of opcodes:
7 init_string Initializes a string variable that is stored in the ~5 temporary variable.
8 Add_string writes the first part of the string.
9 Add_var The string to replace the variable with the write.
第16-28 line.


From here we can see that in the case of using double quotes and using single quotes, the same logic goes through differently (because opcodes is the final execution code for PHP). Just from the number of opcods generated, it is sufficient to prove that it is really quick to use single quotes.


As for the compile phase, the difference between double quotes and single quotes is great, and I'll give you a number to illustrate: in the scanning phase, there are 14 rules for double quotes, and only 6 for single quotes.


Well, after this analysis, you will know better how to use single and double quotes in the future.
By the way, for plain strings that do not require variable substitution, it is well known that double quotes represent strings in C + +, so it is better to use double quotes in this case.
In addition, the attribute values in HTML should be enclosed in double quotes, so don't get used to single quotes, and abuse them everywhere.


See these, I can think of Guang is a quotation mark problem has so much knowledge, is should study hard to avoid later make my headache.


I hope everyone will pay attention to it.








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.