gpt4 book ai didi

PHP 正则表达式将字符串解释为命令行属性/选项

转载 作者:行者123 更新时间:2023-12-02 21:06:47 28 4
gpt4 key购买 nike

假设我有一串

"Insert Post -title Some PostTitle -category 2 -date-posted 2013-02:02 10:10:10"

我一直在尝试做的是将这个字符串转换为操作,该字符串非常可读,我想要实现的目标是使发布变得更容易,而不是每次都导航到新页面。现在我对这些操作的工作方式感到满意,但我已经多次尝试按照我想要的方式处理它,但失败了,我只是希望将属性(选项)之后的值放入数组中,或者简单地提取然后值(value)观将按照我想要的方式处理它们。

上面的字符串应该给我一个键=>值的数组,例如

$Processed = [
'title'=> 'Some PostTitle',
'category'=> '2',
....
];

获得这样的处理数据就是我正在寻找的。

我一直在尝试为此编写一个正则表达式,但没有希望。

例如这个:

 /\-(\w*)\=?(.+)?/

这应该足够接近我想要的。

注意标题和日期中的空格,某些值也可以有破折号,也许我可以添加允许的属性列表

$AllowedOptions = ['-title','-category',...];

我只是不擅长这个,希望得到你的帮助!

感谢!

最佳答案

您可以使用这个基于前瞻的正则表达式来匹配您的名称-值对:

/-(\S+)\h+(.*?(?=\h+-|$))/

RegEx Demo

正则表达式分解:

-                # 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
)

关于PHP 正则表达式将字符串解释为命令行属性/选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35685894/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com