Php 检索带冒号的单词和相关数据
我的数据格式如下:Php 检索带冒号的单词和相关数据,php,regex,Php,Regex,我的数据格式如下: 有些词放在这里优先级:p1,p2-等级:3状态:未延迟 基本上,我需要检索与冒号名称对应的每一组数据 理想情况下,如果我能得到这样一个数组结构 keywords => 'some words go here' priority => 'p1,p2' -rank => 3 status => 'not delayed' 有几点需要注意: 关键字没有定义的冒号(关键字仅放在前面) 关键字并不总是存在(可能只是冒号词) 冒号词并不总是存在(可能只
有些词放在这里优先级:p1,p2-等级:3状态:未延迟
基本上,我需要检索与冒号名称对应的每一组数据
理想情况下,如果我能得到这样一个数组结构
keywords => 'some words go here'
priority => 'p1,p2'
-rank => 3
status => 'not delayed'
有几点需要注意:
感谢您的帮助 正则表达式肯定是一种更优雅的方法,正如@HamZa所展示的,但是这里有一个概念证明来说明,您可以强行解决这个问题。请记住,这是一个概念证明,我不会为您完成整个任务;)
使用preg_split()
:$arr=preg_split('/\s(?=\s+:\s*\s+)/',$str)代码>-.@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
// )