1:数组转字符串
通过implode函数可以将数组通过某字符连接成字符串(下例通过" , "将数组连接成字符串)
<?php $array = array('qq', 'wechat', 'phone'); $comma_separated = implode(",", $array); echo $comma_separated; // 最终打印出的字符串为 qq,wechat,phone // 使用空数组时为空字符串 var_dump(implode('hello', array())); // string(0) "" ?>
2:字符串转数组
通过一个字符串分割另一个字符串,返回一个数组
<?php // 示例 1 $dogs = "dog1 dog2 dog3 dog4 dog5 dog6"; $pieces = explode(" ", $dogs); echo $pieces[0]; // dog1 echo $pieces[1]; // dog2 // 示例 2 $data = "foo:*:1023:1000::/home/foo:/bin/sh"; list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data); echo $user; // foo echo $pass; // * ?>
3:字符串转数组(无分割字符,通过数量控制)
通过str_split函数实现通过字符数量分割字符串,默认一个字符
<?php $str = "Hello World"; $arr1 = str_split($str); //默认以一个字符分割 $arr2 = str_split($str, 3); //每隔3个字符分割 print_r($arr1); print_r($arr2); ?> 输出结果 Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => W [7] => o [8] => r [9] => l [10] => d ) Array ( [0] => Hel [1] => lo [2] => Wor [3] => ld ) ?>
本文为翻滚的胖子原创文章,转载无需和我联系,但请注明来自猿教程iskeys.com