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


Extract name and key from string formatted as array

有没有一种快速简便的方法可以像这样:

job_details[2]

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

,如下所示:
$name='job_details'
$index=2

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

也许

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

使用正则表达式:

// 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()

试试这个:

<?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;
        ?>

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