【发布时间】:2016-02-23 05:25:34
【问题描述】:
有这样一个字符串:
$string = 'connector:rtp-monthly direction:outbound message:error writing data: xxxx yyyy zzzz date:2015-11-02 10:20:30';
此字符串来自用户输入。所以它永远不会有相同的顺序。这是一个输入字段,我需要对其进行拆分以构建数据库查询。
现在我想根据 array() 中给出的单词拆分字符串,这就像一个包含我需要在字符串中找到的单词的映射器。看起来像这样:
$mapper = array(
'connector' => array('type' => 'string'),
'direction' => array('type' => 'string'),
'message' => array('type' => 'string'),
'date' => array('type' => 'date'),
);
只有$mapper 的键是相关的。我尝试过使用 foreach 并像这样爆炸:
$parts = explode(':', $string);
但问题是:字符串中的某处可能有冒号,所以我不需要在那里爆炸。如果在映射器键之后紧跟一个冒号,我只需要爆炸。在这种情况下,映射器键是:
connector // in this case split if "connector:" is found
direction // untill "direction:" is found
message // untill "message:" is found
date // untill "date:" is found
但请记住,用户输入可以变化。所以字符串总是会改变字符串的顺序,mapper array() 永远不会是相同的顺序。所以我不确定爆炸是否是正确的方法,或者我是否应该使用正则表达式。如果是的话怎么做。
所需的结果应该是一个如下所示的数组:
$desired_result = array(
'connector' => 'rtp-monthly',
'direction' => 'outbound',
'message' => 'error writing data: xxxx yyyy zzzz',
'date' => '2015-11-02 10:20:30',
);
非常感谢您的帮助。
【问题讨论】:
-
按空格分割,之后按
: -
它可以用一个正则表达式来完成,你有没有机会将该字符串更改为更容易解析的格式(例如 json 等)?
-
$result = array_column(array_map(function($v){return explode(":", $v);}, explode(" ", $string)), 1, 0); -
/([^:\s]+):(\S+)/两个捕获组,一个在冒号之前,一个在冒号之后。另外使用preg_match_all()。writing和data可以忽略吗? -
意味着您无法控制格式......这太糟糕了,考虑到以下所有答案都涉及更多工作:D