Mithun Sreedharan
Mithun Sreedharan

Reputation: 51272

PHP regular expressions exact data inside brackets

I have some string like Western Australia 223/5 (59.3 ov)

I would like to split this string and extract the following informations with regular expressions

$team = 'Western Australia'
$runs = 223/5
$overs = 59.3

Issue is, format of the text is varying, it may any of the follwing

Any help (like is it possible to have in a single regexp) will be appreciated..

Upvotes: 1

Views: 620

Answers (2)

elitalon
elitalon

Reputation: 9437

Assuming you are using preg_match, you can use the following:

preg_match('/^([\w\s]+)\s*(\d+\/\d+)?\s*(\(\d+\.\d+ ov\))?$/', $input, $matches);

Then, you can inspect $matches to see which one of the options you are supossed to manage was found.

See preg_match documentation for more information.

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

if (preg_match(
    '%^                 # start of string
    (?P<team>.*?)       # Any number of characters, as few as possible (--> team)
    (?:\s+              # Try to match the following group: whitespace plus...
     (?P<runs>\d+       # a string of the form number...
              (?:/\d+)? # optionally followed by /number
     )                  # (--> runs)
    )?                  # optionally
    (?:\s+              # Try to match the following group: whitespace plus...
     \(                 # (
     (?P<overs>[\d.]+)  # a number (optionally decimal) (--> overs)
     \s+ov\)            # followed by ov)
    )?                  # optionally
    \s*                 # optional whitespace at the end
    $                   # end of string
    %six', 
    $subject, $regs)) {
    $team = $regs['team'];
    $runs = $regs['runs'];
    $overs = $regs['overs'];
} else {
    $result = "";
}

You might need to catch an error if the matches <runs> and/or <overs> are not actually present in the string. I don't know much about PHP. (Don't know much biology...SCNR)

Upvotes: 5

Related Questions