提示:很多字符串函數都有start 和 length這兩個參數,當這兩個參數爲正數時,比較好理解,但當爲負數時,則容易出錯。
0代表左邊第一個字符。
-1代表右邊第一個字符
start爲-x時代表從末端向前數第x字符處開始。
length爲-y時代表從末端向前數第y字符截止。
開始字符需要位於結束字符的左端,否則返回空值或者false。
檢測一個字符串是否存在某字符(串)
strstr()
string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )
返回 haystack 字符串從 needle 第一次出現的位置開始到 haystack 結尾的字符串。
若before_needle爲 TRUE,strstr() 將返回 needle 在 haystack 中的位置之前的部分。- stristr()
strstr 函數的忽略大小寫版本 strpos
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
返回 needle 在 haystack 中首次出現的數字位置
stripos()
strpos 函數的忽略大小寫版本
strrpos
int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )
返回字符串 haystack 中 needle 最後一次出現的數字位置
- strripos
strrpos函數的忽略大小寫版本 strrchr 查找單個字符
string strrchr ( string $haystack , mixed $needle )
該函數返回 haystack 字符串中的一部分,這部分以 needle 的最後出現位置開始,直到 haystack 末尾。
字符串的分割
- explode
array explode ( string $delimiter , string $string [, int $limit ] )
此函數返回由字符串組成的數組,每個元素都是 string 的一個子串,它們被字符串 delimiter 作爲邊界點分割出來。
- strtok
string strtok ( string $str , string $token ) string strtok ( string $token )
strtok() 將字符串 str 分割爲若干子字符串,每個子字符串以 token 中的字符分割
split 不支持prel正則語法
array split ( string $pattern , string $string [, int $limit ] )
用正則表達式將字符串分割到數組中
preg_split
array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
通過一個正則表達式分隔字符串
str_split
array str_split ( string $string [, int $split_length = 1 ] )
按照指定長度分割字符串,默認爲1.
chunk_split 不常用
string chunk_split ( string $body [, int $chunklen = 76 [, string $end = "\r\n" ]] )
將字符串分割成小塊
wordwrap
string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )
使用指定寬度分割字符串,如果字符串中沒有空格,且cut參數爲false,那麼此函數將沒有什麼效果,如果cut爲true,則按照指定寬度進行分割,雙字節字符(中文)佔3個寬度位,單字節(英文)佔1個寬度位。
統計字符(串)出現的次數
substr_count
int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
substr_count() 返回子字符串needle 在字符串 haystack 中出現的次數。注意 needle 區分大小寫。
count_chars
mixed count_chars ( string $string [, int $mode = 0 ] )
統計 string 中每個字節值(0..255)出現的次數,使用多種模式返回結果。
str_word_count
mixed str_word_count ( string $string [, int $format = 0 [, string $charlist ]] )
統計 string 中單詞的數量.
字符串替換
str_replace
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
該字符串或數組是將 subject 中全部的 search 都被 replace 替換之後的結果。
substr_replace
mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )
substr_replace() 在字符串 string 的副本中將由 start 和可選的 length 參數限定的子字符串使用 replacement 進行替換。
preg_replace
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
搜索subject中匹配pattern的部分, 以replacement進行替換。
其它常用函數
nl2br
string nl2br ( string $string [, bool $is_xhtml = true ] )
在字符串 string 所有新行之前插入
'<br />'
或'<br>'
,並返回。即將'\n'
替換爲'<br />'
.