1.將字符串轉換為數組的函數:str_split()
array str_split ( string $string [, int $split_length = 1 ] )
-
string:輸入字符串。 -
split_length:每一段的長度。
例子:
$biuuu = 'baidu'; print_r(str_split($biuuu)) ;
輸出結果為:
Array
(
[0] => b [1] => a [2] => i [3] => d [4] => u )
2.將一個一維數組轉換為字符串的函數:implode()
string implode ( string $glue , array $pieces )
glue:默認為空的字符串,鏈接分割后的每個字符串的連接符。pieces:要轉換的字符串。
例子:
$array = array('lastname', 'email', 'phone'); $comma_separated = implode(",", $array); echo $comma_separated; // lastname,email,phone // Empty string when using an empty array: var_dump(implode('hello', array())); // string(0) ""
3.使用一個字符串去分割另外一個字符串:explode()
array explode ( string $delimiter , string $string [, int $limit ] ) //delimiter //邊界上的分隔字符。 //string //輸入的字符串。 //limit //如果設置了 limit 參數並且是正數,則返回的數組包含最多 limit 個元素,而最后那個元素將包含 string 的剩余部分。 //如果 limit 參數是負數,則返回除了最后的 -limit 個元素外的所有元素。 //如果 limit 是 0,則會被當做 1。
例子:
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode(" ", $pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2
4.查找字符串首次出現在某字符中的位置的函數:strpos()或者strstr()
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )
例子:
$mystring = 'abc'; $findme = 'b'; $pos1 = strpos($mystring, $findme); echo $pos1."<br>";//echo 1; $pos2=strstr($mystring,$findme); echo $pos2;//echo bc
strpos返回的是字符串在某個字符串中首次出現的位置;strstr返回的是字符串從出現到某個字符串結束的字符;
如果沒有找到,都會返回false;
5.返回字符串中的字符的函數:substr()
string substr ( string $string , int $start [, int $length ] )
例子:
echo substr('abcdef', 1); // bcdef echo substr('abcdef', 1, 3); // bcd echo substr('abcdef', 0, 4); // abcd echo substr('abcdef', 0, 8); // abcdef echo substr('abcdef', -1, 1); // f // 訪問字符串中的單個字符 // 也可以使用中括號 $string = 'abcdef'; echo $string[0]; // a echo $string[3]; // d echo $string[strlen($string)-1]; // f
6.獲取字符串的長度:strlen()
int strlen ( string $string )
例子:
$str = 'abcdef'; echo strlen($str); // 6 $str = ' ab cd '; echo strlen($str); // 7
