有一个这样的字符串:
$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 并 explode ,如下所示:
$parts = explode(':', $string);
但问题是:字符串中的某个地方可能有冒号,所以我不需要在那里 explode 。如果映射器键后面紧跟着一个冒号,我只需要 explode 。本例中的映射器键是:
connector // in this case split if "connector:" is found
direction // untill "direction:" is found
message // untill "message:" is found
date // untill "date:" is found
但还要记住,用户输入可能会有所不同。因此,字符串总是会改变字符串的顺序,而映射器 array() 永远不会采用相同的顺序。所以我不确定 explode 是否是正确的方法,或者我是否应该使用正则表达式。如果是的话该怎么做。
期望的结果应该是一个看起来像这样的数组:
$desired_result = array(
'connector' => 'rtp-monthly',
'direction' => 'outbound',
'message' => 'error writing data: xxxx yyyy zzzz',
'date' => '2015-11-02 10:20:30',
);
非常感谢您的帮助。
最佳答案
其中更棘手的部分是匹配原始字符串。您可以在 lookahead positive assertions 的帮助下使用正则表达式来完成此操作:
$pattern = "/(connector|direction|message|date):(.+?)(?= connector:| direction:| message:| date:|$)/";
$subject = 'connector:rtp-monthly direction:outbound message:error writing data: xxxx yyyy zzzz date:2015-11-02 10:20:30';
preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER );
$returnArray = array();
foreach($matches as $item)
{
$returnArray[$item[1]] = $item[2];
}
在此正则表达式 /(connector|direction|message|date):(.+?)(?= Connector:| Direction:| message:| date:|$)/
中,您'重新匹配:
(connector|direction|message|date)
- 查找关键字并捕获它;:
- 后跟冒号;(.+?)
- 多次非贪婪地跟随任何字符,并捕获它;(?= 连接器:| 方向:| 消息:| 日期:|$)
- 直到下一个关键字或字符串末尾,使用非捕获前瞻肯定断言.
结果是:
Array
(
[connector] => rtp-monthly
[direction] => outbound
[message] => error writing data: xxxx yyyy zzzz
[date] => 2015-11-02 10:20:30
)
我使用映射器数组并不是为了使示例清晰,但您可以使用 implode
将关键字放在一起。
关于php - 将字符串分解为多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33831515/