Home php教程 php手册 详细介绍在PHP中单引号和双引号的区别

详细介绍在PHP中单引号和双引号的区别

Jun 13, 2016 am 10:14 AM
php introduce about the difference and exist quotation marks article detailed

文章详细的介绍了关于详细介绍在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 $foon"; // 打印结果: foo is 2 (同时换行)

echo 'foo is $foon'; // 打印结果: foo is $foon

$foo = 2;

echo "foo is $foo"; // 打印结果: foo is 2

echo 'foo is $foo'; // 打印结果: foo is $foo

echo "foo is $foon"; // 打印结果: foo is 2 (同时换行)

echo 'foo is $foon'; // 打印结果: foo is $foon   

正如你所看到的,在单引号串中甚至反斜杠也失去了他的扩展含义(除了插入反斜杠\和插入单引号')。所以,当你想在字串中进行变量代换和包 含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:" ' "

字符串之间用 . 来连接

Statement of this Website
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

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why is Bittensor said to be the 'bitcoin' in the AI ​​track? Why is Bittensor said to be the 'bitcoin' in the AI ​​track? Mar 04, 2025 pm 04:06 PM

Original title: Bittensor=AIBitcoin? Original author: S4mmyEth, Decentralized AI Research Original translation: zhouzhou, BlockBeats Editor's note: This article discusses Bittensor, a decentralized AI platform, hoping to break the monopoly of centralized AI companies through blockchain technology and promote an open and collaborative AI ecosystem. Bittensor adopts a subnet model that allows the emergence of different AI solutions and inspires innovation through TAO tokens. Although the AI ​​market is mature, Bittensor faces competitive risks and may be subject to other open source

Is there any difference between South Korean Bitcoin and domestic Bitcoin? Is there any difference between South Korean Bitcoin and domestic Bitcoin? Mar 05, 2025 pm 06:51 PM

The Bitcoin investment boom continues to heat up. As the world's first decentralized digital asset, Bitcoin has attracted much attention on its decentralization and global liquidity. Although China was once the largest market for Bitcoin, policy impacts have led to transaction restrictions. Today, South Korea has become one of the major Bitcoin markets in the world, causing investors to question the differences between it and its domestic Bitcoin. This article will conduct in-depth analysis of the differences between the Bitcoin markets of the two countries. Analysis of the differences between South Korea and China Bitcoin markets. The main differences between South Korea and China’s Bitcoin markets are reflected in prices, market supply and demand, exchange rates, regulatory supervision, market liquidity and trading platforms. Price difference: South Korea’s Bitcoin price is usually higher than China, and this phenomenon is called “Kimchi Premium.” For example, in late October 2024, the price of Bitcoin in South Korea was once

Vertical proxy: Application scenarios and interpretation of disruptive potential of encryption native proxy Vertical proxy: Application scenarios and interpretation of disruptive potential of encryption native proxy Mar 04, 2025 am 10:21 AM

Artificial intelligence agents (AIAgents) are rapidly integrating into daily operations of enterprises, from large companies to small businesses, almost all areas have begun to be used, including sales, marketing, finance, law, IT, project management, logistics, customer service and workflow automation. We are moving from an era of manual processing of data, performing repetitive tasks, and using Excel tables to an era of autonomous operation by AI agents around the clock, which not only improves efficiency but also significantly reduces costs. Application case of AI agents in Web2: YCombinator's Perspective Apten: A sales and marketing optimization tool combining AI and SMS technology. BildAI: A model that can read architectural blueprints,

What exchange is Nexo? Is Nexo exchange safe? What exchange is Nexo? Is Nexo exchange safe? Mar 05, 2025 pm 07:39 PM

Nexo: Not only is it a cryptocurrency exchange, but also your digital financial manager. Nexo is not a traditional cryptocurrency exchange, but a financial platform that focuses more on cryptocurrency lending. It allows users to obtain loans in cryptocurrency as collateral and provides services to earn interest. While Nexo also offers cryptocurrency buying, selling and redemption capabilities, its core business is crypto lending. This article will explore the operating model and security of Nexo in depth to provide investors with a more comprehensive understanding. Nexo's operating model was founded in 2018 and is headquartered in Zug, Switzerland, and is a pioneer in the field of digital finance. It is different from other centralized exchanges and focuses more on providing comprehensive financial services. Users can buy, sell, trade cryptocurrencies without selling assets and

The difference between Ether and Bitcoin What is the difference between Ether and Bitcoin The difference between Ether and Bitcoin What is the difference between Ether and Bitcoin Mar 19, 2025 pm 04:54 PM

The difference between Ethereum and Bitcoin is significant. Technically, Bitcoin uses PoW, and Ether has shifted from PoW to PoS. Trading speed is slow for Bitcoin and Ethereum is fast. In application scenarios, Bitcoin focuses on payment storage, while Ether supports smart contracts and DApps. In terms of issuance, the total amount of Bitcoin is 21 million, and there is no fixed total amount of Ether coins. Each security challenge is available. In terms of market value, Bitcoin ranks first, and the price fluctuations of both are large, but due to different characteristics, the price trend of Ethereum is unique.

What is the difference between the old version of Sesame Open Door Gate and the new version? What is the difference between the old version of Sesame Open Door Gate and the new version? Mar 04, 2025 pm 01:33 PM

The article introduces the difference between the old version of the Sesame Open Door gate.io trading platform and the new version. In terms of interface design, the new version has optimized layout and more modern and simple visual style; in terms of functional experience, transaction functions are upgraded, user experience is optimized, and new functions are added; in terms of security performance, the new version of security mechanism is upgraded, and compliance is improved. However, the actual differences need to be determined by the specific update content of the platform.

Is Bitcoin speculation a stock speculation? Why? What are the differences between the two? Is Bitcoin speculation a stock speculation? Why? What are the differences between the two? Mar 05, 2025 pm 02:24 PM

Bitcoin: Digital gold or stock trading derivatives? In-depth analysis of the nature of its investment. Bitcoin, as an emerging investment method, has drastically fluctuated prices and has similarities with the stock market trading rules, which has triggered people's questions about its investment nature: Is Bitcoin speculation equivalent to stock speculation? This article will discuss in-depth from the aspects of definition, nature, issuance mechanism, etc., and unveil the mystery of Bitcoin investment. Bitcoin and Stocks: The essential difference between Bitcoin and Stocks is: Investing in Bitcoin is not the same as investing in stocks. Bitcoin is a decentralized digital currency that belongs to the category of digital assets or virtual assets. Its transactions are completely controlled by users and adopts a point-to-point (P2P) transmission model to form a decentralized payment system. This concept was proposed by Satoshi Nakamoto in 2009. Unlike traditional currencies,

What is the difference between bean bread and deepseek What is the difference between bean bread and deepseek Mar 12, 2025 pm 01:24 PM

The core difference between bean bun and DeepSeek is retrieval accuracy and complexity. 1. Doubao is based on keyword matching, simple and direct, with low cost, but low accuracy, and is only suitable for structured data; 2. DeepSeek is based on deep learning, can understand semantics, has high accuracy, but high cost, and is suitable for unstructured data. The final choice depends on the application scenario and resource limitations. If the accuracy requirements are not high, choose bean bags, and if you pursue high precision, choose DeepSeek.

See all articles