[PHP] advanced tutorial: difference between double quotes and single quotes in PHP and basic operations of strings

Source: Internet
Author: User
Fields in double quotation marks are interpreted by the compiler and then output as HTML code. The single quotes are output directly without explanation. For example: $ abcmynameistome; echo $ abc: mynameistomecho $ abc: $ abcecho $ abc: mynameistom is especially used in MYSQL statements.

Fields in double quotation marks are interpreted by the compiler and then output as HTML code. ''Is output directly without being interpreted in single quotes. For example: $ abc = 'My name is tome '; echo $ abc // The result is: my name is tomecho' $ abc' // The result is: $ abcecho $ abc // The result is: my name is tom is particularly using MYSQL statements.

"" Fields in double quotation marks are interpreted by the compiler and then output as HTML code.
''Is output directly without being interpreted in single quotes.

For example: 

$ abc = 'my name is tome';

echo $ abc // The result is: my name is tom

echo '$ abc' // The result is: $ abc
echo "$ abc" // The result is: my name is tom

Especially when using MYSQL statements, the use of double quotes and single quotes makes the novice overwhelmed. Here is an example to illustrate.
Assume that a constant is used in the 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'";
Assume that variables are used in the query conditions, for example:
$ user_name = $ _REQUEST ['user_name']; // String variable
$ 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"]. "" ";
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 parts:
1: "select * from table where user_name = '" // Fixed SQL statement
2: $ user // variable
3: "" "
Use "." To connect 1,2,3 parts of strings

First, the quote definition string

PHPIn 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"

PHP parser uses paired quotes to judge a string. Therefore, all strings must use the same single or double
Use quotation marks to define the beginning and end. For example, the following string definitions are illegal:

"I am not a valid string since I have unmatching quote marks'
'Me neither! "

When defining a string, only one type of quote is considered a delimiter, that is, a single quote or a double quote. So if a string is quoted by double
Start, then only double quotes are parsed by the parser. This way you can include any other characters in the double quoted string, even single quotes
number. The following quoted strings are all legal:
$ s = "I am a 'single quote string' inside a double quote string";
$ s = 'I am a "double quote string" inside a single quote string';

PHPWhen PHP encounters the quotation mark corresponding to the beginning of the string, it thinks that the end of the string has been reached, so:

"Why doesn't" this "work?"

Is actually divided into three parts by the PHP parser:

"Why doesn't"-a double-quoted string containing a single quote
this-extra characters that the parser cannot handle
"work?"-ordinary string

例子 The above example attempts to include double quotes in the double quoted string, and the parser considers the string to be a string when it encounters the second double quoted string.
It's gone. To achieve the purpose of including quotes, the parser must ignore its original meaning when encountering ordinary quotes in the string.
Add a backslash to tell PHP: the quotes are part of the string, the correct way is:

"Why doesn't \" that \ "work?"

一个 A common problem in English strings is the use of the apostrophe ', because it is a single quote, which is very common in English strings.
(English possessive). You have to be careful with these characters:

'You \' d better escape your apostrophes'

You can see that the backslash has its special meaning in the string. When we need to include the backslash itself in the string, we need to
The symbol is preceded by an extra backslash. E.g:
$ file = "c: \ windows \ system.ini";
echo $ file; // The result is: c: windowssystem.ini
$ file = "c: \\ windows \\ system.ini";
echo $ file; // The print result is: c: \ windows \ system.ini
Another way to define strings is to eliminate the trouble of special characters and facilitate the quote of longer text. The string defines the party
The method starts with the << symbol immediately following a custom string, and the last line ends with the custom string, and must be spaced.

Second, the connection of strings
Strings can be concatenated with a string concatenation (.), Such as:
$ first_name = 'Charlie';
$ last_name = 'Brown';
$ full_name = $ first_name. ''. $ last_name;

Common use is to create large HTML string codes. Assignment numbers (=) and connectors (.) Can be combined into (. =)
Number, such as:
$ html = '';
$ html. = '';
for ($ i = 0; $ i <10; $ i ++) {
$ square = $ i * $ i;
$ html. = '';
$ html. = '
number square
'. $ i.' '. $ square.'

Using variables in strings

This feature saves you from having to use concatenation to stick and smash a lot of simple strings. PHP allows us to include words directly in double quoted strings
String variables, we can find that the processing results of the following two strings are the same.

$ full_name = $ first_name. ''. $ last_name;
$ full_name = "$ first_name $ last_name";
Single and double quoted strings are handled differently in PHP. The contents of double quoted strings can be interpreted and replaced, while single quotes
The contents of a number string are always considered ordinary characters. E.g:
$ foo = 2;
echo "foo is $ foo"; // prints the result: foo is 2
echo 'foo is $ foo'; // prints the result: foo is $ foo
echo "foo is $ foo \ n"; // prints the result: foo is 2 (also newline)
echo 'foo is $ foo \ n'; // prints the result: foo is $ foo \ n
As you can see, even backslashes lose their extended meaning in single quoted strings (except for inserting backslash \\ and inserting
quotation marks\'). So, when you want to do variable substitution in strings and include escape sequences such as \ n (newline characters), you should use double quotes
number. Single quoted strings can be used anywhere else. Single quoted strings are faster in scripts because PHP parsers
The processing of single-quoted strings is relatively simple, and the processing of double-quoted strings is more complicated because the strings also need to be parsed, so the processing speed is faster
Slightly slower.

引用 When referring to a complex combination of variables in a string, some problems may occur, the following code will work properly:
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 the use of these strings, we usually separate complex variables from strings, like this:
echo 'value ='. $ a [$ i] [$ j];
Another way is to enclose complex variables in curly braces so that the parser will recognize them correctly:
echo "value = {$ a [$ i] [$ j]}" // Print an element of the two-dimensional array $ a
In this way, new problems have arisen. When we want to quote the curly bracket character itself in a string, remember to use the escape character:
$ var = 3;
echo "value = {$ var}"; // prints the result "value = 3"
echo "value = \ {$ var}"; // prints the result "value = {3}"
Slashes and SQL statements

Generating HTML code or SQL query statements is often encountered when writing PHP programs and is an interesting thing. 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 for this type of code

Let's look at an example. If you want to query the user whose name is "O'Keefe" in the database, usually the form of SQL statement
Is such that:
select * from users where last_name = 'O \' Keefe '
Please note that the English possessive (apostrophe) of the SQL statement must be escaped with a backslash. PHP specifically provides some functions to handle this
In this case, the purpose of the function AddSlashes ($ str) is to automatically insert the backslash escape character for the quote character in the string:

$ last_name = "O'Keefe";
$ sql = "select * from users where last_name = '". addslashes ($ last_name). "'";
In this example, you also need to enclose single quotes around the last_name string (required by SQL syntax), because the double is used here
The quoted string, so there is no need to escape the pair of single quotes. The following statement is the equivalent using a single quoted string:
$ sql = 'select * from users where last_name = \' '. addslashes ($ last_name).' \ '';
Any time you want to write a string in the database, you must ensure that the quotes inside use the escape symbol correctly, this is a lot of PHP
Common mistakes for beginners.

Fourth, double quotes and HTML

Different from SQL statements, double quotes are often used to represent strings in standard HTML language (many browsers now have strong fault tolerance
Yes, it allows single quotes or even unquoted strings in HTML), for example:
$ html = ''. $ link. '';
$ html = "$ link";
HTML language does not support backslash escaping. This will be realized when we use the form's hidden inputs to transfer data. The best way to set the value of hidden inputs is to use the htmlspecialchars () function for encoding. The following statement can
For normal transmission of data that may contain double quotes:

People often ask me, I heard that processing strings with PHP in single quotes will be faster. If variable substitution exists, is it faster to use single quotes or double quotes? The simple answer is obviously pale and weak. Today we will do an experiment to see what is the difference between single quotes and double quotes, who is faster and who is slower.

The test code is as follows:

Next, let's take a look at the Opcodes generator mentioned in the previous article, and finally how our code is executed:

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 extreturn 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
8 ADD_STRING ~ 5 ~ 5, 'This + is + a +'
9 ADD_VAR ~ 5 ~ 5,! 2
10 ASSIGN! 4, ~ 5
11 11 ECHO! 3
12 12 ECHO! 4
14 13 ASSIGN! 2, 'This'
16 14 CONCAT ~ 8! 2, '+ is + a + String'
15 ASSIGN! 5, ~ 8
17 16 INIT_STRING ~ 10
17 ADD_VAR ~ 10 ~ 10,! 2
18 ADD_STRING ~ 10 ~ 10, '+ is + a + String'
19 ASSIGN! 6, ~ 10
19 20 ECHO! 5
20 21 ECHO! 6
22 22 RETURN 1
Note the 0th to 3rd op lines, it can be seen that without variable substitution, the double-quoted and single-quoted Opcodes are the same.
Let's take a look again: Articles 4 to 12 can be found that in the case of variable substitution, the Opcodes generated by using double quotes and single quotes are different. Let's analyze the Opcodes in the case of double quotes:
7 INIT_STRING initializes a string variable, stored in ~ 5 temporary variables.
8 ADD_STRING writes the first part of the string.
9 ADD_VAR Writes a string replaced by a variable.
Lines 16-28 are similar.

From this we can find that the execution of the same logic in the case of using double quotes and the case of using single quotes is really different (because Opcodes is the final code execution for PHP). From the number of Opcods generated, it is enough to prove that it is indeed faster to use single quotes.

As for the compilation phase, the difference between double quotes and single quotes is also very large. I will use a number to explain: In the scanning stage, there are 14 lexical rules for double quotes, and only 6 for single quotes.

For the W3C standard, attribute values in HTML should be enclosed in double quotes, so don't get used to single quotes and abuse them everywhere.

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.