PHP拆分字符串

时间:2014-02-13 15:58:55

标签: php regex

所以我有以下字符串:

{family:Open Sans,name:Open Sans,import_family:Open+Sans:300,300italic,regular,italic,600,600italic,700,700italic,800,800italic,classname:opensans}

我想“矢量化”它,所以它可能看起来像这样:

XX['family'] = "Open Sans',
XX['name'] = 'Open Sans',
XX['import_family'] = 'Open+Sans:300,300italic,regular,italic,600,600italic,700,700italic,800,800italic',
XX['classname'] = 'opensans';

关于如何在PHP中实现这一点的任何想法?这让我很紧张,在过去的几个小时里一直试着用正则表达式来解决这个问题,到目前为止还没有结果。

提前致谢!

2 个答案:

答案 0 :(得分:1)

以下是您可以使用的此格式的简单解析器。它将处理所有字段和值,并将它们作为键/值数组返回。它假定字符串以花括号开头和结尾,并使用field:optional:optional,a,b,c格式。

<?php
    header('Content-Type: text/plain');

    function parse($str) {
        $obj = [];

        $str = substr($str, 1, -1);
        $candidates = explode(',', $str);

        $lastKey = null;

        foreach ($candidates as $candidate) {
            if (strpos($candidate, ':')) {
                $parts = explode(':', $candidate);
                $key = $parts[0];
                $value = substr($candidate, strlen($key) + 1);

                $obj[$key] = $value;
                $lastKey = $key;
            } else {
                $obj[$lastKey] .= ',' . $candidate;
            }
        }

        return $obj;
    }

    $example = '{family:Open Sans,name:Open Sans,import_family:Open+Sans:300,300italic,regular,italic,600,600italic,700,700italic,800,800italic,classname:opensans}';
    print_r(parse($example));
?>

您指定的示例字符串的输出:

Array
(
    [family] => Open Sans
    [name] => Open Sans
    [import_family] => Open+Sans:300,300italic,regular,italic,600,600italic,700,700italic,800,800italic
    [classname] => opensans
)

答案 1 :(得分:1)

试试这个:

$s = "{family:Open Sans,name:Open Sans,import_family:Open+Sans:300,300italic,regular,italic,600,600italic,700,700italic,800,800italic,classname:opensans}";
$s = rtrim(ltrim($s, '{'), '}');

preg_match_all('#([^:,]+):((?:(?!(,[^:,]+:)).)*)#', $s, $matches);
$vector = array_combine($matches[1], $matches[2]);

修改

正如HamZa解释here,正则表达式更短:

([^:,]+):(.+?)(?=,[^,]+:|$)