我需要从字符串(PHP)生成数组

时间:2015-01-15 11:29:52

标签: php arrays string

我跟着字符串:

$str = "  father    mother brother   sister  ";

我需要获得包含4个元素的数组:"父亲","母亲","兄弟"和"姐姐"

5 个答案:

答案 0 :(得分:3)

这应该适合你:

<?php

    $str = "  father    mother brother   sister  ";
    $parts = preg_split('/\s+/', $str, -1, PREG_SPLIT_NO_EMPTY);
    print_r($parts);

?>

输出:

Array ( [0] => father [1] => mother [2] => brother [3] => sister )

答案 1 :(得分:2)

如果单词之间有多个,可能是可变长度的空格,最简单的方法是使用preg_split

$array = preg_split('/ +/', "  father    mother brother   sister  ", -1, PREG_SPLIT_NO_EMPTY);

测试:

php > $array = preg_split('/ +/', "  father    mother brother   sister  ", -1, PREG_SPLIT_NO_EMPTY);
php > var_dump($array);
array(4) {
  [0]=>
  string(6) "father"
  [1]=>
  string(6) "mother"
  [2]=>
  string(7) "brother"
  [3]=>
  string(6) "sister"
}

如果要按任何空格(包括标签和新行)拆分,可以尝试:

$array = preg_split('/\s+/', "  father    mother brother   sister  ", -1, PREG_SPLIT_NO_EMPTY);

答案 2 :(得分:1)

使用explode()将字符串拆分为以空格字符()分隔的片段,然后将返回的数组传递给array_filter()以删除空片段(您的字符串包含多个连续的分隔符)最后使用array_values()删除键(array_filter()后它们仍然稀疏)并重新编号从0开始的项目:

$str = "  father    mother brother   sister  ";
$array = array_values(array_filter(explode(' ', $str)));

print_r($array);

输出:

Array
(
    [0] => father
    [1] => mother
    [2] => brother
    [3] => sister
)

答案 3 :(得分:0)

试试这个:

$str = "  father    mother brother   sister  ";
$tmpArr = explode(' ',$str);
$newArr = array();
foreach ($tmpArr AS $v) {if (!empty($v)) {$newArr[] = $v;}}
var_dump($newArr);

答案 4 :(得分:-1)

<?php
$result = explode(' ',$str);
array_walk($result,'trim');
function trim($str){
   $str = trim($str);
}
?>