加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php中单引号与双引号定义字符串的区别分析

发布时间:2020-12-13 05:15:43 所属栏目:PHP教程 来源:网络整理
导读:①转义的字符不同 单引号和双引号中都可以使用转义字符(\),但只能转义在单引号中引起来的单引号和转义转义符本身。如果用双引号()括起字符串,PHP懂得更多特殊字符串的转义序列。 $str1 = '\',\\,\r\n\t\v\$\"'; echo $str1,' '; $str2 = "\",a

①转义的字符不同

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

$str1 = '\',\\,\r\n\t\v\$\"';

echo $str1,'
';

$str2 = "\",a\r\n\tb\v\$\'";

echo $str2,'
';

?>

②对变量的解析不同

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

$age = 20;

$str1 = 'I am $age years old';

$str2 = "I am $age years old";

echo $str1,'
'; // I am $age years old

echo $str2,'
'; // I am 20 years old;

?>

③解析速度不同

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

反斜杠

//使用单引号

echo ' this \n is \r the blog \t of \\ zhoumanhe \\';

//上面使用单引号输出的值是 this \n is \r the blog \t of \ zhoumanhe \

echo '

';

echo "

";

//使用双引号

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

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

使用sql

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

select?* from abc_table where user_name=’abc’;

SQL语句可以写成:

SQLstr = “select * from abc_table where user _name= ‘abc’”

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

$user_name = $_REQUEST['user_name']; //字符串变量

$user=array (”name”=> $_REQUEST['user_name‘,"age"=>$_REQUEST['age'];//数组变量


SQL语句就可以写成:

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可以分解为以下3个部分:

1:”select * from table where user_name = ‘ ” //固定SQL语句


2:$user //变量


3:” ‘ ”

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读