提示:很多字符串函数都有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 />'
.