从格式化为数组的字符串中提取名称和键

时间:2013-10-14 03:56:18

标签: php arrays

是否有一种快速简便的方法可以解决这样的问题:

job_details[2]

这是一个字符串,在两个变量中,$ name和$ index这样:

$name='job_details'
$index=2

编辑:为了澄清,我被赋予job_details [2]作为字符串,就是这样。我想将job_details位提取到一个新变量中,并将2位提取到一个新变量中。显然我可以使用正则表达式做到这一点,但我想知道是否有更好的解决方案。

3 个答案:

答案 0 :(得分:2)

也许

$name = strtok($input, "[");
$index = strtok("]");

答案 1 :(得分:0)

使用正则表达式:

// Search the string
preg_match_all('/([_\w]*)\[([^]]*)\]/', 'job_title[1], job_details[2]', $matches);

// $matches[1] holds your values
// $matches[2] holds your keys
print_r($matches);

// Combine then into a nice array
$data = array_combine($matches[2], $matches[1]);

print_r($data);

这应该是输出:

Array
(
    [0] => Array
        (
            [0] => job_title[1]
            [1] => job_details[2]
        )

    [1] => Array
        (
            [0] => job_title
            [1] => job_details
        )

    [2] => Array
        (
            [0] => 1
            [1] => 2
        )

)
Array
(
    [1] => job_title
    [2] => job_details
)

供参考:preg_match_all()array_combine()

答案 2 :(得分:0)

试试这个:

<?php
        $string = 'job_details[2]';
        $str_arr = explode('[', $string);

        $var_value = $str_arr[0];
        $index_value = $str_arr[1];
        $index_value = trim($str_arr[1], '[]');
        echo $var_value."<br />";

        echo $index_value;
        ?>

您可以在字符串中使用不同的特殊字符。它也会工作。