php 字符串的 split 和 join, 字符串根据某个字符分割成数组,一个数组通过某个字符组合成一个字符串,如处理文件路径:
“this is a test for string”
通过 “\” 进行分割,得到的结果应该是:
this
is
a
test
for
string
然后又想通过 “=” 把数组连成一个新的字符串,结果应该是:
this=is=a=test=for=string
在 C# 中可以通过 String 的 Split() 和 Join() 方法来实现,如下:
String content = "this is a test for string";
Console.WriteLine(content);
String[] array = content.Split(' ');
foreach (var item in array) {
Console.WriteLine(item.ToString());
}
content = String.Join("=", array);
Console.WriteLine(content);
结果如下:

但是 PHP 里没有 Split() 和 Join() 方法,与之对应的是:
explode() ——- Split() ——— 分割
implode() ——- Join() ——— 组成
所以用 php 来实现相同的需求:
<?php
$test = 'this is a test for string';
$result1 = explode(' ', $test);
var_dump($result1);
$result2 = implode('=', $result1);
var_dump($result2);
结果如下:

我们继续深入做一些测试:
<?php
$test = 'this is a test for string';
//添加其他测试
//1. explode() 分割,如果分割的字符并不在字符串中
$result2 = explode(',', $test);// $test 中没有逗号
var_dump($result2);
//2. implode() 组成,如果数组只有一个元素,不会添加组成的字符
$test_array1 = array(
'apple',
);
$result3 = implode(' -> ', $test_array1);
var_dump($result3);
结果如下:

总结:
explode() 函数是将字符串 按给定的标志 来分割成数组,如果字符串中没有该标志,结果是不会分割的,结果仍为原字符串;
implode() 函数是将 数组的元素,按给定的标志 链接成字符串,当数组只有一个元素时,是不会产生连接效果的。
相关阅读: