函數 | 描述 | 使用 $subject=Hello World | 返回值 |
---|---|---|---|
strtoupper() | 將字符串轉為大寫 | strtoupper($subject ) | HELLO WORLD |
strtolower() | 將字符串轉為小寫 | strtolower($subject ) | hello world |
ucfirst() | 如果字符串第一個字符是字符,將其轉為大寫 | ucfirst($subject ) | Hello world |
ucwords() | 將字符串的每個單詞的首字母大寫 | ucwords($subject ) | Hello World |
二、用字符串函數連接和分割字符串
1、用函數explode()、implode()和join()
exlpode()
把字符串打散為數組:
!DOCTYPE html> html> body> ?php $str = "Hello world. I love Shanghai!"; print_r (explode(" ",$str)); ?> /body> /html>
結果
Array ( [0] => Hello [1] => world. [2] => I [3] => love [4] => Shanghai! )
implode()
(jion()
是implode()
函數的別名)
把數組元素組合為字符串:
!DOCTYPE html> html> body> ?php $arr = array('Hello','World!','I','love','Shanghai!'); echo implode(" ",$arr); ?> /body> /html>
結果
Hello World! I love Shanghai!
2、使用strtok()函數
strtok()
函數把字符串分割為更小的字符串(標記)。
語法
strtok(string,split)
參數 | 描述 |
---|---|
string | 必需。規定要分割的字符串。 |
split | 必需。規定一個或多個分割字符。 |
!DOCTYPE html> html> body> ?php $string = "Hello world. Beautiful day today."; $token = strtok($string, " "); while ($token !== false) { echo "$tokenbr>"; $token = strtok(" "); } ?> /body> /html>
結果
Hello
world.
Beautiful
day
today.
3、使用substr()函數
定義和用法
substr()
函數返回字符串的一部分。
注釋:如果 start 參數是負數且 length 小于或等于 start,則 length 為 0。
語法
substr(string,start,length)
參數 | 描述 |
---|---|
string | 必需。規定要返回其中一部分的字符串。 |
start | 必需。規定在字符串的何處開始。
|
length | 可選。規定被返回字符串的長度。默認是直到字符串的結尾。
|
!DOCTYPE html> html> body> ?php echo substr("Hello world",6); ?> /body> /html>
結果
world
!DOCTYPE html> html> body> ?php echo substr("Hello world",10)."br>"; echo substr("Hello world",1)."br>"; echo substr("Hello world",3)."br>"; echo substr("Hello world",7)."br>"; echo substr("Hello world",-1)."br>"; echo substr("Hello world",-10)."br>"; echo substr("Hello world",-8)."br>"; echo substr("Hello world",-4)."br>"; ?> /body> /html>
結果
d
ello world
lo world
orld
d
ello world
lo world
orld
!DOCTYPE html> html> body> ?php echo substr("Hello world",0,10)."br>"; echo substr("Hello world",1,8)."br>"; echo substr("Hello world",0,5)."br>"; echo substr("Hello world",6,6)."br>"; echo substr("Hello world",0,-1)."br>"; echo substr("Hello world",-10,-2)."br>"; echo substr("Hello world",0,-6)."br>"; echo substr("Hello world",-2-3)."br>"; ?> /body> /html>
結果
Hello worl
ello wor
Hello
world
Hello worl
ello wor
Hello
world
三、字符串的比較
1、strcmp()比較兩個字符串,如果相等,函數返回0
!DOCTYPE html> html> body> ?php echo strcmp("Hello world!","Hello world!"); ?> /body> /html>
結果
0
2、strlen()函數測試字符串的長度
!DOCTYPE html> html> body> ?php echo strlen("Shanghai"); ?> /body> /html>
結果
8
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php常用函數與技巧總結》、《php字符串(string)用法總結》、《PHP數組(Array)操作技巧大全》、《PHP基本語法入門教程》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。