1、數組轉字符串
implode
方法介紹:
function implode ($glue = "", array $pieces) {}
主要有兩個參數
一個是連接符(glue:膠水的意思),默認是空字符串
一個是數組
使用
$test = array("hello","world","php"); echo implode("-",$test);
結果:
hello-world-php
$test = array("h"=>"hello","w"=>"world","p"=>"php"); echo implode("-",$test);
2、字符串分割成數組
2.1 按某個字符分割
function explode ($delimiter, $string, $limit = null) {}
explode
參數解釋:
delimiter,分隔符
limit
文檔google翻譯結果:
如果limit設置為正,則返回的數組將包含最大限制元素,最后一個元素包含字符串的其余部分。
limit 限制分割的份數,最后一份為剩下的字符串分割后剩下的,當然如果為1的話,就是字符串本身(已經過實驗)
代碼演示:
$str="hello-world-php"; $result = explode("-", $str); var_dump($result); $result = explode("-", $str,2); var_dump($result);
輸出結果:
array(3) { [0]=> string(5) "hello" [1]=> string(5) "world" [2]=> string(3) "php" } array(2) { [0]=> string(5) "hello" [1]=> string(9) "world-php" }
2.2 按距離讀取
可能字符串不用分割,但是需要把每個字符拿出來,也就是一個一個讀出來
** * Convert a string to an array * @link http://php.net/manual/en/function.str-split.php * @param string $string <p> * The input string. * </p> * @param int $split_length [optional] <p> * Maximum length of the chunk. * </p> * @return array If the optional split_length parameter is * specified, the returned array will be broken down into chunks with each * being split_length in length, otherwise each chunk * will be one character in length. * </p> * <p> * false is returned if split_length is less than 1. * If the split_length length exceeds the length of * string, the entire string is returned as the first * (and only) array element. * @since 5.0 */ function str_split ($string, $split_length = 1) {}
數組如果指定了可選的split_length參數,則返回的數組將被分解為長度為split_length的塊,否則每個塊將是一個字符長度。
$str = "hello"; var_dump(str_split($str,2)); 1 2 array(3) { [0]=> string(2) "he" [1]=> string(2) "ll" [2]=> string(1) "o" }