PHP中單引號與雙引號的區別

PHP中,我們可以使用單引號或者雙引號來表示字符串。不過我們作爲開發者,應該瞭解其中的區別。單引號與雙引號對於定義字符一個是可以解析變量一個是會把變量直接輸出來,同時單引號與雙引號在字符處理上單引號要優與雙引號.

PHP中單引號與雙引號的區別

  ①轉義的字符不同

單引號和雙引號中都可以使用轉義字符(\),但只能轉義在單引號中引起來的單引號和轉義轉義符本身。如果用雙引號(“”)括起字符串,PHP懂得更多特殊字符串的轉義序列。

<?php

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

echo $str1,'<br />';

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

echo $str2,'<br />';

?>

②對變量的解析不同

單引號字符串中出現的變量不會被變量值替代。即PHP不會解析單引號中的變量,而是將變量名原樣輸出。雙引號字符串最重要的`一點是其中的變量名會被變量值替代,即可以解析雙引號中包含的變量。

<?php

$age = 20;

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

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

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

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

?>

③解析速度不同

單引號不需要考慮變量的解析,速度比雙引號快.推薦用單引號.有的時候雙引號也比較好用,比如在拼湊sql 語句

反斜槓

?

1

2

3

4

5

6

7

8

9

10

11

12

//使用單引號

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

假設查詢條件中使用的是常量,例如:

?

1

select * from abc_table where user_name='abc';

SQL語句可以寫成:

?

1

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

假設查詢條件中使用的是變量,例如:

?

1

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

?

1

$user=array (”name”=> $_REQUEST['user_name‘,"age"=>$_REQUEST['age'];//數組變量

SQL語句就可以寫成:

?

1

2

SQLstr = “select * from abc_table where user_name = ‘ ” . $user_name . ” ‘ “;

SQLstr = “select * from abc_table where user_name = ‘ ” . $user["name"] . ” ‘ “;

對比一下:

?

1

2

3

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

2

3

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

2:$user //變量

3:” ‘ ”

附:大家也看到了 echo '<br/>'; html中的標籤在單引號和雙引號中都有效。

總結一下PHP引號使用原則

1.字符串的值用引號

中儘量用單引號,HTML代碼全部用雙引號

3.在包含變量的時候,用雙引號可以簡化操作

4.複雜的情況下用大括號包起來

PHP引號還有一個用處就是,有的時候需要用php生成文本文件,換行符n需要用雙引號才能好使,單引號則會直接把n當成字符輸出。

使用總結:在字符串裏面不需要加入 變量 或者 單引號(')和反斜槓(\) 時,儘量用單引號引字符串,因爲省去了雙引號檢查處理轉義和解析變量上面的時間。能用單引號儘量用單引號。