Home > php教程 > php手册 > body text

php中单引号与双引号定义字符串的不同

WBOY
Release: 2016-05-23 13:07:23
Original
1986 people have browsed it

单引号与双引号对于定义字符一个是可以解析变量一个是会把变量直接输出来,同时单引号与双引号在字符处理上单引号要优与双引号哦.

①转义的字符不同

单引号和双引号中都可以使用转义字符(\),但只能转义在单引号中引起来的单引号和转义转义符本身,如果用双引号("")括起字符串,PHP懂得更多特殊字符串的转义序列,代码如下:

<?php 
$str1 = &#39;\&#39;,\\,\r\n\t\v\$\"&#39;; 
echo $str1,&#39;<br />&#39;; 
$str2 = "\",\\,a\r\n\tb\v\$\&#39;"; 
echo $str2,&#39;<br />&#39;;
Copy after login

②对变量的解析不同

单引号字符串中出现的变量不会被变量值替代,即PHP不会解析单引号中的变量,而是将变量名原样输出,双引号字符串最重要的一点是其中的变量名会被变量值替代,即可以解析双引号中包含的变量,代码如下:

<?php 
$age = 20; 
$str1 = &#39;I am $age years old&#39;; 
$str2 = "I am $age years old"; 
echo $str1,&#39;<br />&#39;; // I am $age years old  
echo $str2,&#39;<br />&#39;; // I am 20 years old;
Copy after login

③解析速度不同

单引号不需要考虑变量的解析,速度比双引号快.推荐用单引号.有的时候双引号也比较好用,比如在拼凑sql 语句.

反斜杠代码如下:

//使用单引号 
echo &#39; this \n is \r the blog \t of \\ zhoumanhe \\&#39;;  
//上面使用单引号输出的值是 this \n is \r the blog \t of \ zhoumanhe \ 
echo &#39; 
&#39;; 
echo " 
";
Copy after login

//使用双引号

echo "this \n is \r the blog \t of \\ zhoumanhe \\";
Copy after login

//上面使用双引号输出的值是 this is the blog of \ zhoumanhe \

使用sql代码如下,假设查询条件中使用的是常量,例如:

select * from abc_table where user_name=&#39;abc&#39;;
Copy after login

SQL语句可以写成:

SQLstr = "select * from abc_table where user _name= &#39;abc&#39;" ;
Copy after login

假设查询条件中使用的是变量,例如:

$user_name = $_REQUEST[&#39;user_name&#39;]; //字符串变量
Copy after login

$user=array ("name"=> $_REQUEST[&#39;user_name&#39;,"age"=>$_REQUEST[&#39;age&#39;];//数组变量 
SQL语句就可以写成: 
SQLstr = "select * from abc_table where user_name = &#39; " . $user_name . " &#39; "; 
SQLstr = "select * from abc_table where user_name = &#39; " . $user["name"] . " &#39; "; 
对比一下: 
SQLstr="select * from abc_table where user_name = &#39; abc &#39; " ; 
SQLstr="select * from abc_table where user_name =&#39; " . $user _name . " &#39; "; 
SQLstr="select * from abc_table where user_name =&#39; " . $user["name"] . " &#39; ";
Copy after login

SQLstr可以分解为以下3个部分:

1:"select * from table where user_name = ' " //固定SQL语句

2:$user //变量

3:" ' "

附:大家也看到了 echo '
'; html中的标签在单引号和双引号中都有效。

总结一下PHP引号使用原则

1.字符串的值用引号

2.PHP中尽量用单引号,HTML代码全部用双引号

3.在包含变量的时候,用双引号可以简化操作

4.复杂的情况下用大括号包起来

PHP引号还有一个用处就是,有的时候需要用php生成文本文件,换行符n需要用双引号才能好使,单引号则会直接把n当成字符输出.

使用总结:在字符串里面不需要加入 变量 或者 单引号(')和反斜杠(\) 时,尽量用单引号引字符串,因为省去了双引号检查处理转义和解析变量上面的时间,能用单引号尽量用单引号.


Related labels:
source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!