在php中要分割字符串常用的有二個函數,chunk_split,explode還有一個str_split函數,這個三了,下面看實例。
定義和用法
chunk_split() 函數把字符串分割為一連串更小的部分。
語法:chunk_split(string,length,end)
參數:string 必需,規定要分割的字符串。
參數:length 可選,一個數字,定義字符串塊的長度。
參數:end 可選,字符串值,定義在每個字符串塊之后放置的內容。
- */
- $data="hello world! this is a world!"; //定義字符串
- $new_string=chunk_split($data); //分割字符串
- echo $new_string; //輸出結果
- /*
定義和用法
explode() 函數把字符串分割為數組。
語法:explode(separator,string,limit)
參數:string 必需,要分割的字符串。
參數:limit 可選,規定所返回的數組元素的最大數目。
- */
- $str='one|two|three|four'; //定義字符串
- $result=explode('|',$str,2); //切開字符串
- print_r($result); //輸出結果
- $result=explode('|',$str,-1); //以負數為返回個數
- print_r($result); //輸出結果
- /*
定義和用法
str_split() 函數把字符串分割到數組中。
語法:str_split(string,length)
參數:length 可選,規定每個數組元素的長度,默認是 1。
- $str="hello world"; //定義字符串
- $result=str_split($str); //執行轉換操作
- print_r($result); //輸出轉換后的結果
- $result=str_split($str,4); //每個元素定長為4
- print_r($result); //輸出轉換后的結果
新聞熱點
疑難解答