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
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助