假设我有一串
"Insert Post -title Some PostTitle -category 2 -date-posted 2013-02:02 10:10:10"
Run Code Online (Sandbox Code Playgroud)
我一直在尝试做的是将这个字符串转换为操作,该字符串非常可读,我想要实现的目标是使发布变得更容易,而不是每次都导航到新页面。现在我对这些操作的工作方式感到满意,但我已经多次尝试按照我想要的方式处理它,但失败了,我只是希望将属性(选项)之后的值放入数组中,或者简单地提取然后价值观将按照我想要的方式处理它们。
上面的字符串应该给我一个键=>值的数组,例如
$Processed = [
'title'=> 'Some PostTitle',
'category'=> '2',
....
];
Run Code Online (Sandbox Code Playgroud)
我正在寻找这样的处理数据。
我一直在尝试为此编写一个正则表达式,但没有希望。
例如这个:
/\-(\w*)\=?(.+)?/
Run Code Online (Sandbox Code Playgroud)
这应该足够接近我想要的。
请注意标题和日期中的空格,某些值也可以有破折号,也许我可以添加允许的属性列表
$AllowedOptions = ['-title','-category',...];
Run Code Online (Sandbox Code Playgroud)
我只是不擅长这个,希望得到你的帮助!
赞赏!
您可以使用这个基于前瞻的正则表达式来匹配您的名称-值对:
/-(\S+)\h+(.*?(?=\h+-|$))/
Run Code Online (Sandbox Code Playgroud)
正则表达式分解:
- # 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
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
输出:
Array
(
[title] => Some PostTitle
[category] => 2
[date-posted] => 2013-02:02 10:10:10
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
430 次 |
| 最近记录: |