[英]PHP Regex to interpret a string as a command line attributes/options
假设我有一串
"Insert Post -title Some PostTitle -category 2 -date-posted 2013-02:02 10:10:10"
我一直想做的就是将该字符串转换为动作,该字符串可读性强,而我试图实现的目的是使发布变得容易一些,而不是每次都导航到新页面。 现在我可以确定这些动作将如何进行,但是我尝试了很多失败的尝试,只是希望将属性(选项)后的值放入数组中,或者简单地将其提取价值观然后将以我想要的方式处理它们。
上面的字符串应该给我一个键=>值的数组,例如
$Processed = [
'title'=> 'Some PostTitle',
'category'=> '2',
....
];
得到这样的处理后的数据是我想要的。
我一直在尝试为此编写一个正则表达式,但没有希望。
例如:
/\-(\w*)\=?(.+)?/
那应该足够接近我想要的。
注意标题和日期中的空格,并且某些值也可以带有破折号,也许我可以添加允许属性的列表
$AllowedOptions = ['-title','-category',...];
我只是不擅长此事,并希望得到您的帮助!
感谢!
您可以使用基于前瞻的正则表达式来匹配您的名称/值对:
/-(\S+)\h+(.*?(?=\h+-|$))/
正则表达式分解:
- # match a literal hyphen
(\S+) # match 1 or more of any non-whitespace char and capture it as group #1
\h+ # match 1 or more of any horizontal whitespace char
( # capture group #2 start
.*? # match 0 or more of any char (non-greedy)
(?=\h+-|$) # lookahead to assert next char is 1+ space and - or it is end of line
) # capture group #2 end
PHP代码:
$str = 'Insert Post -title Some PostTitle -category 2 -date-posted 2013-02:02 10:10:10';
if (preg_match_all('/-(\S+)\h+(.*?(?=\h+-|$))/', $str, $m)) {
$output = array_combine ( $m[1], $m[2] );
print_r($output);
}
输出:
Array
(
[title] => Some PostTitle
[category] => 2
[date-posted] => 2013-02:02 10:10:10
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.