使用特定的Regex规则将单个字符串拆分为数组

时间:2013-04-19 05:22:04

标签: php regex

我正在处理包含许多数据对的单个字符串。每对由;符号分隔。每对包含一个数字和一个字符串,以=符号分隔。

我认为这很容易处理,但我发现字符串中的一半字符串可以包含=;符号,这使得简单的拆分不可靠。

以下是有问题字符串的示例:

123=one; two;45=three=four;6=five;

为了正确处理,我需要将其拆分为如下所示的数组:

'123', 'one; two'
'45',  'three=four'
'6',   'five'

我有点死路,所以感谢任何帮助。

更新

感谢大家的帮助,这是我到目前为止所处的位置:

$input = '123=east; 456=west';

// split matches into array
preg_match_all('~(\d+)=(.*?);(?=\s*(?:\d|$))~', $input, $matches);

$newArray = array();

// extract the relevant data
for ($i = 0; $i < count($matches[2]); $i++) {
    $type   = $matches[2][$i];
    $price  = $matches[1][$i];

    // add each key-value pair to the new array
    $newArray[$i] = array(
        'type'      => "$type",
        'price'     => "$price"
    );
}

哪个输出

Array
(
    [0] => Array
        (
            [type] => east
            [price] => 123
        )

)

第二项缺失,因为它最后没有分号,我不知道如何解决这个问题。

我现在意识到该对的数字部分有时包含一个小数点,并且最后一个字符串对后面没有分号。任何提示都会受到赞赏,因为我没有太多运气。

这是更新后的字符串,考虑到我在初始问题中遗漏的内容(抱歉):

12.30=one; two;45=three=four;600.00=five

5 个答案:

答案 0 :(得分:1)

我认为这是你想要的正则表达式:

\s*(\d+)\s*=(.*?);(?=\s*(?:\d|$))

诀窍是只考虑以数字作为匹配结尾的分号。这就是最终的前瞻性。

您可以在www.debuggex.com上看到详细的可视化效果。

答案 1 :(得分:1)

您可以使用以下preg_match_all代码捕获:

$str = '123=one; two;45=three=four;6=five;';
if (preg_match_all('~(\d+)=(.+?);(?=\d|$)~', $str, $arr))
   print_r($arr);

现场演示:http://ideone.com/MG3BaO

答案 2 :(得分:1)

$str = '123=one; two;45=three=four;6=five;';

preg_match_all('/(\d+)=([a-zA-z ;=]+)/', $str,$matches);
echo '<pre>';
print_r($matches);
echo '</pre>';

O / P:

Array
(
    [0] => Array
        (
            [0] => 123=one; two;
            [1] => 45=three=four;
            [2] => 6=five;
        )

    [1] => Array
        (
            [0] => 123
            [1] => 45
            [2] => 6
        )

    [2] => Array
        (
            [0] => one; two;
            [1] => three=four;
            [2] => five;
        )

)

然后你可以结合

echo '<pre>';
print_r(array_combine($matches[1],$matches[2]));
echo '</pre>';

O / P:

Array
(
    [123] => one; two;
    [45] => three=four;
    [6] => five;
)

答案 3 :(得分:1)

你需要一个先见的断言;如果;之后是数字或字符串的结尾,那么前瞻匹配:

$s = '12.30=one; two;45=three=four;600.00=five';

preg_match_all('/(\d+(?:.\d+)?)=(.+?)(?=(;\d|$))/', $s, $matches);

print_r(array_combine($matches[1], $matches[2]));

输出:

Array
(
    [12.30] => one; two
    [45] => three=four
    [600.00] => five
)

答案 4 :(得分:0)

试试这个,但是这段代码是用c#编写的,你可以把它改成php

 string[] res = Regex.Split("123=one; two;45=three=four;6=five;", @";(?=\d)");

- SJ