将字符串转换为json

时间:2014-01-04 21:45:15

标签: php regex json

我有一个带时间戳(24小时制)和电视节目名称的字符串,格式如下:

21.45 Batman 23.30 The Hour 00.20 Newsfeed 04.00 Otherfeed 21.55 Soccer: USA - Spain 23.30 The Wire

字符串可以是任意长度,我不能以任何方式修改字符串。我仍然希望以一种我需要它的方式使用字符串作为json。字符串始终采用相同的格式。

我的目标是将字符串转换为以下内容:

{
  "shows": [
    {
        "show": "Batman",
        "time": "21.45"
    },
    {
        "show": "The Hour",
        "time": "23.30"
    },
    {
        "show": "Newsfeed",
        "time": "00.20"
    },
    {
        // etc...
    }
  ]
}

我用PHP做这个,我真的很喜欢regexp,它在2014年我的学习列表上很高:)

2 个答案:

答案 0 :(得分:2)

$code = '21.45 Batman 23.30 The Hour 00.20 Newsfeed 04.00 Otherfeed 21.55 Soccer: USA - Spain 23.30 The Wire';

preg_match_all('~(?P<time>\d+[.]\d+)\s*(?P<show>.*?)(?=\s*\d+[.]\d+|$)~', $code, $codeSplit);

$shows = array();
for($i = 0; $i <= count($codeSplit['time']); $i++) {
    $shows[] = array('show' => $codeSplit['show'][$i], 'time' => $codeSplit['time'][$i]);
}

$json = json_encode(array('shows' => $shows));


var_dump($json);

答案 1 :(得分:2)

<?php

$string = '21.45 Batman 23.30 The Hour 00.20 Newsfeed 04.00 Otherfeed 21.55 Soccer: USA - Spain 23.30 The Wire';

$floatPattern = '/[-+]?[0-9]*(\.[0-9]+)/';

preg_match_all($floatPattern, $string, $numbers);
$numbers = $numbers[0];

$names = preg_split($floatPattern, $string);

$result = array();

foreach ($numbers as $k => $v) {
    $result[] = array('show' => $names[$k+1], 'time' => $v);
}

echo json_encode(array('shows' => $result));