2

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

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

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

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
4

5 回答 5

1

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

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

诀窍是仅将后跟数字的分号视为匹配的结尾。这就是最后的前瞻性。

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

于 2013-04-19T05:35:05.957 回答
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

于 2013-04-19T05:49:01.263 回答
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;
)
于 2013-04-19T06:19:34.090 回答
1

为此,您需要一个前瞻断言;如果 a;后跟一个数字或字符串的结尾,则前瞻匹配:

$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
)
于 2013-04-19T08:55:37.520 回答
0

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

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

--SJ

于 2013-04-19T05:43:15.110 回答