将字符串的部分提取到数组

时间:2017-12-22 07:03:38

标签: php arrays regex string preg-match

我有一个字符串,我需要爆炸并获取信息。

示例字符串:

"20' Container 1, 40' Open Container 1, 40-45' Closed Container 3"

首先,我按,爆炸字符串并获取

"20' Container 1"
"40' Open Container 1"
"40-45' Closed Container 3"

现在我想要爆炸已爆炸的数组,以便我得到以下格式的结果

array[
    0 => [
        0 => "20'"
        1 => "Container"
        2 => "1"
        ]
    1 => [
        0 => "40'"
        1 => "Open Container"
        2 => "1"
        ]
    ]

字符串可能会有所不同,但决定格式相同,例如length type number

3 个答案:

答案 0 :(得分:1)

您可以再次爆炸以获得所需的数组,

$str = "20' Container 1, 40' Open Container 1, 40-45' Closed Container 3";
$result = array();
$temp= explode(", ",$str);
array_walk($temp, function($item, $key) use(&$result) {
    $result[$key] = explode(" ", $item);
});
print_r($result);

以下是demo

答案 1 :(得分:1)

使用逗号分隔符循环分解字符串,然后将length type number上的每个匹配项推送到结果数组

$string = "20' Container 1, 40' Open Container 1, 40-45' Closed Container 3";

$result = [];
$pattern = '/([\d-]*\')\s(.*)\s(\d+)/';
foreach (explode(', ', $string) as $value) {
    preg_match($pattern, $value, $matches); // Match length, type, number
    $result[] = array_slice($matches, 1);   // Slice with offset 1
}

print_r($result);

答案 2 :(得分:0)

另一种方法:

$str = "20' Container 1, 40' Open Container 1, 40-45' Closed Container 3";
preg_match_all("/(\d+(?:-\d+)?')\s+([a-z\s]+)\s(\d+)(?:, )?/i", $str, $match);
for($i = 0; $i <3; $i++) {
    $final[] = array_slice(array_column($match, $i), 1);
}
print_r($final);

<强>输出:

Array
(
    [0] => Array
        (
            [0] => 20'
            [1] => Container
            [2] => 1
        )

    [1] => Array
        (
            [0] => 40'
            [1] => Open Container
            [2] => 1
        )

    [2] => Array
        (
            [0] => 40-45'
            [1] => Closed Container
            [2] => 3
        )

)

<强>正则表达式:

/               : regex delimiter
  (             : start group 1
    \d+         : 1 or more digits
    (?:-\d+)?   : non capture group, a dash followed by digits, optional
    '           : 'single quote
  )             : end group 1
  \s+           : 1 or more spaces
  (             : start group 2
    [a-z\s]+    : 1 or more alphabetic or space
  )             : end group 2
  \s+           : 1 or more spaces
  (             : start group 3
    \d+         : 1 or more digits
  )             : end group 3
  (?:, )?       : non capture group, a comma followed by space, optional
/i              : regex delimiter, case insensitive