Emad Ha
Emad Ha

Reputation: 1222

PHP Regex to interpret a string as a command line attributes/options

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 !

Upvotes: 2

Views: 430

Answers (1)

anubhava
anubhava

Reputation: 785128

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
)

Upvotes: 5

Related Questions