检索带有冒号的单词和相关数据


Retrieving words with colon, and associated data

我的数据格式如下:

some words go here priority: p1,p2 -rank:3 status: not delayed

基本上,我需要检索与冒号名称对应的每组数据。

理想情况下,如果我最终能得到一个数组结构,这样

keywords => 'some words go here'
priority => 'p1,p2'
-rank    => 3
status   => 'not delayed'

注意事项:

  1. 关键字将没有定义冒号(关键字只是放在前面)

  2. 关键字并不总是存在(可能只是冒号字)

  3. 冒号不一定存在(可能只是关键字)

我认为必须使用正则表达式来解析它,但这超出了我对正则表达式的理解。如果有更简单的方法,我很乐意找到。任何帮助,感谢!

正则表达式当然是一种更优雅的方法,正如@HamZa所展示的那样,但是这里有一个概念证明来说明您可以使用暴力强制解决方案。请记住,这是一个概念证明,我不会为你做你的整个作业;)

<?php
$string = "keywords go here priority: p1,p2 -rank:3 status: not delayed";
$kv = array();
$key = "keywords";
$substrings = explode(":", $string);
foreach($substrings as $k => $substring) {
        $pieces = explode(" ", $substring);
        $chunk = $k == count($substrings) - 1 ? 0 : 1;
        $kv[$key] = trim(join(" ", array_slice($pieces, 0, count($pieces)-$chunk)));
        $key = $pieces[count($pieces)-1];
}
print_r($kv);
// Array
// (
//   [keywords] => keywords go here
//   [priority] => p1,p2
//   [-rank] => 3
//   [status] => not delayed
// )