PHP将编号的字符串列表转换为数组

时间:2012-09-29 17:42:10

标签: php regex arrays

使用PHP,如果你有一个string在点之后可能有或没有空格,例如:

"1. one 2.too 3. free 4. for 5.five "

您可以使用哪种功能创建array,如下所示:

array(1 => "one", 2 => "too", 3 => "free", 4 => "for", 5 => "five") 

密钥是列表项目编号(例如上面的array没有0

我假设需要一个正则表达式,也许使用preg_split或类似的?我对正则表达式很糟糕,所以任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:2)

怎么样:

$str = "1. one 2.too 3. free 4. for 5.five ";
$arr = preg_split('/\d+\./', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($arr);

答案 1 :(得分:-1)

我得到了一个快速黑客,它似乎对我来说很好

        $string = "1. one 2.too 3. free 4. for 5.five ";

    $text_only = preg_replace("/[^A-Z,a-z]/",".",$string);
    $num_only = preg_replace("/[^0-9]/",".",$string);

    $explode_nums = explode('.',$num_only);
    $explode_text = explode('.',$text_only);

    foreach($explode_text as $key => $value)
    {
        if($value !== '' && $value !== ' ')
        {
            $text_array[] = $value;
        }
    }

    foreach($explode_nums as $key => $value)
    {
        if($value !== '' && $value !== ' ')
        {
            $num_array[] = $value;
        }
    }

    foreach($num_array as $key => $value)
    {
        $new_array[$value] = $text_array[$key];
    }

    print_r($new_array);

测试一下,让我知道如果工作正常

相关问题