dre75230 2016-02-28 17:37
浏览 70
已采纳

PHP Regex将字符串解释为命令行属性/选项

let's say i have a string of

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

what i've been trying to do is to convert this string into actions, the string is very readable and what i'm trying to achieve is making posting a little bit easier instead of navigating to new pages every time. Now i'm okay with how the actions are going to work but i've had many failed attempts to process it the way i want, i simple want the values after the attributes (options) to be put into arrays, or simple just extract the values then ill be dealing with them the way i want.

the string above should give me an array of keys=>values, e.g

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

getting a processed data like this is what i'm looking for.

i've been tryin to write a regex for this but with no hope.

for example this:

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

that should be close enought to what i want.

note the spaces in title and dates, and that some value can have dashes as well, and maybe i can add a list of allowed attributes

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

i'm just not good at this and would like to have your help!

appreciated !

  • 写回答

1条回答 默认 最新

  • dongque1958 2016-02-28 18:18
    关注

    You can use this lookahead based regex to match your name-value pairs:

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

    RegEx Demo

    RegEx Breakup:

    -                # 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 Code:

    $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);
    }
    

    Output:

    Array
    (
        [title] => Some PostTitle
        [category] => 2
        [date-posted] => 2013-02:02 10:10:10
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?