search
HomeBackend DevelopmentPHP TutorialPHP 单引号与双引号的区别_php技巧

1、定义字符串   

在PHP中,字符串的定义可以使用单引号,也可以使用双引号。但是必须使用同一种单或双引号来定义字符串,如:‘Hello"和“Hello'为非法的字符串定义。   
定义字符串时,只有一种引号被视为定义符,即单引号或双引号。于是,如果一个字符串由双引号开始,那么只有双引号被分析器解析。这样,你就可以在双引号串中包含任何其他字符,甚至单引号。下面的引号串都是合法的:
Php代码
复制代码 代码如下:

$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';   

而串 "Why doesn't "this" work?" 则会被分为三段。如果在这个串中想要表示出双引号,则可以使用转义符"\"(反斜线),变成 "Why doesn't \"this\" work?" 即可。

2、字符串变量中的单、双引号  
 
PHP允许我们在双引号串中直接包含字串变量,我们可以发现下面的两个字串的处理结果是相同的。
复制代码 代码如下:

$full_name = $first_name . ' ' . $last_name;
$full_name = "$first_name $last_name";   

单引号串和双引号串在PHP中的处理是不相同的。双引号串中的内容可以被解释而且替换,而单引号串中的内容总被认为是普通字符。例如:
Php代码
复制代码 代码如下:

$foo = 2;
echo "foo is $foo"; // 打印结果: foo is 2
echo 'foo is $foo'; // 打印结果: foo is $foo
echo "foo is $foo\n"; // 打印结果: foo is 2 (同时换行)
echo 'foo is $foo\n'; // 打印结果: foo is $foo\n
$foo = 2;
echo "foo is $foo"; // 打印结果: foo is 2
echo 'foo is $foo'; // 打印结果: foo is $foo
echo "foo is $foo\n"; // 打印结果: foo is 2 (同时换行)
echo 'foo is $foo\n'; // 打印结果: foo is $foo\n   

正如你所看到的,在单引号串中甚至反斜杠也失去了他的扩展含义(除了插入反斜杠\和插入单引号\')。所以,当你想在字串中进行变量代换和包 含 (换行符)等转义序列时,你应该使用双引号。单引号串可以用在其他任何地方,脚本中使用单引号串处理速度会更快些,因为PHP语法分析器对单引号串 的处理方式比较单纯,而双引号的处理由于串内部也需要解析,因此更复杂些,所以处理速度略慢。   
在字符串中引用复杂的变量组合时,可能会产生一些问题,下面的代码会正常工作:
Php代码
复制代码 代码如下:

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

而下面的代码却不能得到我们希望的结果:
echo "value = $a[$i][$j]"; //我们希望打印二维数组$a的某个元素。   
为避免这些字串使用中的潜在问题,我们通常把复杂的变量从字串中分离开来,就像这样:echo 'value = ' . $a[$i][$j];//字符串的连接用点(.)   
还有一种办法是将复杂变量用花括号括起来,语法分析器就能正确辨认了:
echo "value = {$a[$i][$j]}" //打印二维数组$a的某个元素   
这样,又出现新问题了。当我们想在字串中引用花括号字符本身时,就要记得使用转义符了:
Php代码
复制代码 代码如下:

$var = 3;
echo "value = {$var}"; // 打印结果 "value = 3"
echo "value = \{$var}"; // 打印结果 "value = {3}"
$var = 3;
echo "value = {$var}"; // 打印结果 "value = 3"
echo "value = \{$var}"; // 打印结果 "value = {3}"


3、在SQL语句中  
 
这是会经常遇到的问题,在插入数据库的SQL语句是采用单引号来定义字符串,如果要将一个含有单引号的字符串插入数据库,这个SQL语句就会出错。
如:$sql="insert into userinfo (username,password) Values('O'Kefee','123456')"   
此时,处理的方法之一是在SQL语句中加入转义符反斜线,
即:……Values('O\'Kefee',……   
当然也可以使用函数 addslashes(),该函数的功能就是加入转义符,
即:$s = addslashes("O'Kefee") ……Values('".$s."',……   
还有一种方法是设置php.ini中的magic-quotes选项,打开该选项,则通过表单提交的信息中如果有单引号是,将会自动加上如转义符。因此不用使用其他函数了。
补充: 这就要从双引号和单引号的作用讲起: 双引号里面的字段会经过编译器解释然后再当作HTML代码输出,但是单引号里面的不需要解释,直接输出。
例如:
复制代码 代码如下:

$abc='I love u';
echo $abc //结果是:I love u
echo '$abc' //结果是:$abc
echo "$abc" //结果是:I love u

所以在对数据库里面的SQL语句赋值的时候也要用在双引号里面SQL="select a,b,c from ..." 但是SQL语句中会有单引号把字段名引出来
例如:select * from table where user='abc';
这里的SQL语句可以直接写成SQL="select * from table where user='abc'"
但是如果象下面:
复制代码 代码如下:

$user='abc';
SQL1="select * from table where user=' ".$user." ' ";对比一下
SQL2="select * from table where user=' abc ' "

我把单引号和双引号之间多加了点空格,希望你能看的清楚一点。
也就是把'abc' 替换为 '".$user."'都是在一个单引号里面的。只是把整个SQL字符串分割了。 SQL1可以分解为以下3个部分
1:"select * from table where user=' "
2:$user
3:" ' "
字符串之间用 . 来连接,这样能明白了吧。 

一、引号定义字符串

  在PHP中,通常一个字符串被定义在一对引号中,如:
'I am a string in single quotes'
"I am a string in double quotes"
  PHP语法分析器是用成对的引号来判断一个字符串的。因此,所有字符串必须使用同一种单或者双
引号来定义开始和结束。例如,下面的字串定义是不合法的:
"I am not a valid string since I have unmatching quote marks'
'Me neither!"
  定义字符串时,只有一种引号被视为定义符,即单引号或双引号。于是,如果一个字符串由双引
号开始,那么只有双引号被分析器解析。这样,你就可以在双引号串中包含任何其他字符,甚至单引
号。下面的引号串都是合法的:
$s = "I am a 'single quote string' inside a double quote string";
$s = 'I am a "double quote string" inside a single quote string';
  当PHP遇到与串的开头相对应的引号时,便认为已经到了字符串尾部,于是:
"Why doesn't "this" work?"
  实际上被PHP语法分析器分成三个部分:
"Why doesn't "——包含一个单引号的双引号串
this——多余的字符,分析器无法处理
" work?" ——普通字符串
  上面的这个例子企图在双引号串中包含双引号,而分析器在遇到第二个双引号时便认为字符串结
束了。要达到包含引号的目的,必须分析器在遇到串内普通引号的时候忽略它的原意,我们在引号的
前面加上一个反斜杠来告诉PHP:这个引号是字符串的一部分,正确的表示方法是这样:
"Why doesn't \"that\" work?"
  在英文字符串中一个常见的问题是撇号'的使用,因为它就是一个单引号,而在英文串中十分常见
(英文所有格)。你必须小心处理这些字符:
'You\'d better escape your apostrophes'
  可以看到反斜杠在字符串中有他的特殊含义,当我们需要在字符串中包含反斜杠本身时,需要在
该符号前面多加一个反斜杠。例如:
$file = "c:\windows\system.ini";
echo $file; // 打印结果为: c:windowssystem.ini
$file = "c:\\windows\\system.ini";
echo $file; // 打印结果为: c:\windows\system.ini
  另一种字符串定义方式,能够消除特殊字符的烦恼,而且便于引用较长的文本。该字符串定义方
法以
二、字串的连接

  字串可以使用字串连接符(.)来连接,如:
$first_name = 'Charlie';
$last_name = 'Brown';
$full_name = $first_name . ' ' . $last_name;
  常见的用途是建立大块的HTML字串代码,赋值号 (=) 连接符 (.) 可以被简写合并为 (.=) 符
号,如:
$html = '';
$html .= '';
for ( $i=0 ; $i$square = $i * $i;
$html .= '';
}
$html .= '
number square
' . $i . ' ' . $square . '
';

三、在字串中使用变量

  这个功能让你无须使用连接符号来粘和大量的简单字符串。PHP允许我们在双引号串中直接包含字
串变量,我们可以发现下面的两个字串的处理结果是相同的。
$full_name = $first_name . ' ' . $last_name;
$full_name = "$first_name $last_name";
  单引号串和双引号串在PHP中的处理是不相同的。双引号串中的内容可以被解释而且替换,而单引
号串中的内容总被认为是普通字符。例如:
$foo = 2;
echo "foo is $foo"; // 打印结果: foo is 2
echo 'foo is $foo'; // 打印结果: foo is $foo
echo "foo is $foo\n"; // 打印结果: foo is 2 (同时换行)
echo 'foo is $foo\n'; // 打印结果: foo is $foo\n
  正如你所看到的,在单引号串中甚至反斜杠也失去了他的扩展含义(除了插入反斜杠\和插入单
引号\')。所以,当你想在字串中进行变量代换和包含\n(换行符)等转义序列时,你应该使用双引
号。单引号串可以用在其他任何地方,脚本中使用单引号串处理速度会更快些,因为PHP语法分析器对
单引号串的处理方式比较单纯,而双引号的处理由于串内部也需要解析,因此更复杂些,所以处理速
度略慢。
  在字符串中引用复杂的变量组合时,可能会产生一些问题,下面的代码会正常工作:
echo "value = $foo";
echo "value = $a[$i]";
  而下面的代码却不能得到我们希望的结果:
echo "value = $a[$i][$j]"; //我们希望打印二维数组$a的某个元素。
  为避免这些字串使用中的潜在问题,我们通常把复杂的变量从字串中分离开来,就像这样:
echo 'value = ' . $a[$i][$j];
  还有一种办法是将复杂变量用花括号括起来,语法分析器就能正确辨认了:
echo "value = {$a[$i][$j]}" //打印二维数组$a的某个元素
  这样,又出现新问题了。当我们想在字串中引用花括号字符本身时,就要记得使用转义符了:
$var = 3;
echo "value = {$var}"; // 打印结果 "value = 3"
echo "value = \{$var}"; // 打印结果 "value = {3}"

三、斜杠和SQL语句

  生成HTML代码或SQL查询语句是编写PHP程序时经常遇到而且是件有趣的事情。为什么这么说呢,
因为这涉及到生成另外一种类型的代码,你必须仔细地考虑和遵循这种代码所要求的编写语法和规
则。
  我们来看这样一个例子,假如你想查询数据库中名字是“O'Keefe”的用户,通常SQL语句的形式
是这样的:
select * from users where last_name = 'O\'Keefe'
  请注意SQL语句这个英文所有格(撇号)需使用反斜杠转义。PHP专门提供了一些函数来处理这样
的情况,函数AddSlashes($str)的用途就是自动在字串中对引号字符插入反斜杠转义符:
$last_name = "O'Keefe";
$sql = "select * from users where last_name = '" . addslashes($last_name) . "'";
  在这个例子中,你还要在last_name字串外面括上单引号(SQL语法要求),由于这里使用的是双
引号串,所以对这对单引号就无须使用转义了。下面的这个语句是使用单引号串的等价形式:
$sql = 'select * from users where last_name = \'' . addslashes($last_name) . '\'';
  任何时候你要在数据库中写入字串,你都必须确保里面的引号正确使用了转义符号,这是很多PHP
初学者常犯的错误。

四、双引号和HTML

  与SQL语句不同,在标准HTML语言中双引号常被用来表示字串(现在很多浏览器具备较强的容错功
能,允许在HTML中用单引号甚至不用引号表示字符串),例如:
$html = ''.$link.'';
$html = "$link";
  HTML语言不支持反斜杠转义,这一点在我们使用表单的hidden inputs来传输数据的时候就会有所
体会了。设置hidden inputs的值的最好办法,是使用htmlspecialchars()函数来编码。下面的语句可
以正常传输一个可能包含双引号的数据:
  

一、引号定义字符串。要达到包含引号的目的, 必须分析器在遇到串内普通引号的时候忽略它的原意,我们在引号的 前面加上一个反斜杠来告诉PHP:这个引号是字符串的一部分,正确的表示方法是这样:单引号串可以用在其他任何地方,脚本中使用单引号串处理速度会更快些,因为PHP语法分析器对 单引号串的处理方式比较单纯,而双引号的处理由于串内部也需要解析,因此更复杂些,所以处理速 度略慢。

这个...双引号转义,单引号不转义
如:/r/n是换行,但是如果你用单引号写入文件,不会是换行,而是一个字符,如果用双引号写入文件,就是换行.
同意。
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function