一、substr函數
1、substr函數指定起始位置截取指定長度的字符串。
2、語法:substr(string $string, int $start, int|null $length=null): string|null
其中,$string為要截取的字符串,$start為起始位置,$length為可選參數,表示截取的長度。
<?php $str = 'Hello World!'; echo substr($str, 6)."
"; // 輸出: World! echo substr($str, 3, 5)."
"; // 輸出: lo Wo ?>
二、explode函數
1、explode函數將一個字符串按指定的分隔符分割成數組。
2、語法:explode(string $delimiter, string $string, int|null $limit=null): array
其中,$delimiter為分隔符,$string為要分割的字符串,$limit為可選參數,表示限制返回的數組元素個數。
apple [1] => banana [2] => orange [3] => watermelon ) ?>
三、str_split函數
1、str_split函數將一個字符串按指定長度分割成數組。
2、語法:str_split(string $string, int $length=1): array
其中,$string為要分割的字符串,$length為可選參數,表示分割的長度,默認為1。
ab [1] => cd [2] => ef [3] => g ) ?>
四、preg_split函數
1、preg_split函數將一個字符串按指定正則表達式分割成數組。
2、語法:preg_split(string $pattern, string $subject, int|null $limit=null, int $flags=0): array
其中,$pattern為正則表達式,$subject為要分割的字符串,$limit為可選參數,表示限制返回的數組元素個數,$flags為可選參數,表示用於改變函數行為的標記。
orange [1] => apple [2] => banana [3] => pear ) ?>
五、chunk_split函數
1、chunk_split函數將一個字符串按指定長度分割成多個字符串。
2、語法:chunk_split(string $string, int $length=76, string $end=”\r\n”): string
其中,$string為要分割的字符串,$length為可選參數,表示分割的長度,默認為76,$end為可選參數,表示分割後每個字符串末尾的字符,默認為「\r\n」。
<?php $str = 'abcdefghijklmnopqrstuvwxyz'; echo chunk_split($str, 5)."
"; // 輸出:abcde fghij klmno pqrst uvwxy z ?>
六、總結
字符串分割是字符串處理中非常常用且重要的一個功能,php中提供了多種分割函數,供我們根據實際需求進行選擇使用。substr函數適用於簡單的字符串截取,explode函數適用於按分隔符進行分割,str_split函數適用於按指定長度分隔,preg_split函數適用於按正則表達式分割,chunk_split函數適用於按指定長度分割成多個字符串。
原創文章,作者:YOIEX,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/370738.html