这篇文章主要介绍“PHP中数组和字符串是如何进行转换的”,在日常操作中,相信很多人在PHP中数组和字符串是如何进行转换的问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”PHP中数组和字符串是如何进行转换的”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
方法介绍:
function implode ($glue = "", array $pieces) {}
主要有两个参数
一个是连接符(glue:胶水的意思),默认是空字符串
一个是数组
$test = array("hello","world","php");
echo implode("-",$test);
结果:
hello-world-php
如果是K-V形式的数组呢?
$test = array("h"=>"hello","w"=>"world","p"=>"php");
echo implode("-",$test);
结果还是
hello-world-php
说明还是只对value有作用。
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"
}
可能字符串不用分割,但是需要把每个字符拿出来,也就是一个一个读出来
原文档:
**
* 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的块,否则每个块将是一个字符长度。
Convert a string to an array,这不就是把字符串转为数组嘛,用法没啥可说的
现在我想试一试,如果是5个长度的字符串,按两位读取,不足两位时,最后一位是否保留?
当然推测来说为了数据的完整性,应该是要保留的。
$str = "hello";
var_dump(str_split($str,2));
结果也正如我的推测
array(3) {
[0]=>
string(2) "he"
[1]=>
string(2) "ll"
[2]=>
string(1) "o"
}
到此,关于“PHP中数组和字符串是如何进行转换的”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。