最近由於數據庫大作業的到來,我又不得不去搞php+mysql了,對mysql的使用也就僅限能正確使用“增”,“刪”,“改”,“更”了。而實際上也只需要會這么點,最難的還是php的編寫。之前一直沒認真研究php,今天實在沒辦法了,發現php中字符串的拼接用的實在是太多了。所以特意去研究了一發,整理下筆記。
首先和大家說下,學習任何一門語言都要去官網去看文檔,因為官方的文檔正確性有保證,並且也最有廣泛性。這里就給出官方的文檔鏈接http://php.net/manual/zh/language.operators.string.php#41950。如果有登不上的,就繼續往下看我的筆記吧。
有兩個字符串(string)運算符。第一個是連接運算符(“.”),它返回其左右參數連接后的字符串。第二個是連接賦值運算符(“.=”),它將右邊參數附加到左邊的參數之后。
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>
$var = 3;
echo "Result:" . $var + 3;
?>
運行后發現只輸出了一個 ‘3’,為什么呢?
因為第一字符串“Result3”被創建,這然后被添加到3得到3,非空非數字字符串被轉換為0。如果要輸出"Result: 6",則代碼如下:
$var = 3;
echo "Result:" . ($var + 3);
?>
下面的例子---
如果試圖用連接運算符加號,你的結果將是這些數字為字符串的結果。
echo "thr"."ee"; //prints the string "three"
echo "twe" . "lve"; //prints the string "twelve"
echo 1 . 2; //prints the string "12"
echo 1.2; //prints the number 1.2
echo 1+2; //prints the number 3
?>
大括號服務好替代串聯,和他們更快地輸入和代碼看起來更干凈。
記得用雙引號(“”)而不是單引號(‘’)作為其內容是由PHP parced,因為在單引號(''),你會得到所提供的變量litaral名稱
$a = '12345';
// This works:
echo "qwe{$a}rty"; // qwe12345rty, using braces
echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used
// Does not work:
echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
echo "qwe$arty"; // qwe, because $a became $arty, which is undefined
?>
$var = "hello";
$world = "world";
echo "$var" . '$world'; //outputs hello$world
echo "$var" . "$world"; //outputs helloworld
echo "$var" . $world; //outputs helloworld
?>
可以看出使用使用(‘’)即把單引號里的內容作為了字符,直接echo出來了。而使用(“”)則保留了變量。