本文主要是介绍利用php的explode函数将字符串按分隔符(比如空格)分拆并组装在数组中-----要考虑连续空格问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
看php:
<?php$str = "Hello world. I love php!";$arr = explode(" ", $str);print_r($arr);
?>
结果:
Array
(
[0] => Hello
[1] => world.
[2] => I
[3] => love
[4] => php!
)
但当空格较多时候, 就有问题了, 如下:
<?php$str = "Hello world. I love php!";$arr = explode(" ", $str);print_r($arr);
?>
结果:
Array
(
[0] => Hello
[1] =>
[2] =>
[3] =>
[4] =>
[5] => world.
[6] =>
[7] =>
[8] =>
[9] => I
[10] => love
[11] =>
[12] =>
[13] => php!
)
这显然不是期望的结果, 其中有太多空元素了。 应该改为:
<?php$str = "Hello world. I love php!";$arr = explode(" ", $str);$arr = array_filter($arr); // 删除空元素print_r($arr);foreach($arr as $value){$newArr[] = $value;}print_r($newArr);
?>
结果为:
Array
(
[0] => Hello
[5] => world.
[9] => I
[10] => love
[13] => php!
)
Array
(
[0] => Hello
[1] => world.
[2] => I
[3] => love
[4] => php!
)
方法多多, 如上仅为一种。
这篇关于利用php的explode函数将字符串按分隔符(比如空格)分拆并组装在数组中-----要考虑连续空格问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!