Christoffer
Christoffer

Reputation: 492

Match number with special character next to it

I have a string that can look in different ways.

$str = "11:00 Team1 - Team2 0-0"
$str = "4' Team1 - Team2 2-1"
$str = "Half time Team1 - Team2 2-1"
$str = "55' Team1 - Team2 3-1"
$str = "Finished Team1 - Team2 2-1"

By using regex, I would like to know when the string contains "Number+:+Number", "Number+'" and none of the two previous combinations. Furthermore I would like to extract "Number+-+Number".

I've tried this for the 2nd example:

preg_match("/[0-9+']/", $str)

Upvotes: 0

Views: 66

Answers (3)

Jørgen R
Jørgen R

Reputation: 10806

The correct expression to match all cases would be

\d+[:'-]\d*

It matches one or more digits, then either a colon, ' or dash, then zero or more digits.

PHP example

$str[] = "11:00 Team1 - Team2 0-0";
$str[] = "4' Team1 - Team2 2-1";
$str[] = "Half time Team1 - Team2 2-1";
$str[] = "55' Team1 - Team2 3-1";
$str[] = "Finished Team1 - Team2 2-1";

foreach($str as $s) {
    preg_match_all("/\d+[:'-]\d*/", $s, $res);
    print_r($res);
}

prints

Array ( [0] => Array ( [0] => 11:00 [1] => 0-0 ) )
Array ( [0] => Array ( [0] => 4' [1] => 2-1 ) )
Array ( [0] => Array ( [0] => 2-1 ) )
Array ( [0] => Array ( [0] => 55' [1] => 3-1 ) )
Array ( [0] => Array ( [0] => 2-1 ) )

Live fiddle

Upvotes: 0

James Coyle
James Coyle

Reputation: 10398

These are the regular expressions you need:

For the first: (Number + : + Number)

/[0-9]+:[0-9]+/

For the second: (Number + ')

/[0-9]+'/

For the third: (Number + - + Number)

/[0-9]+-[0-9]+/

Upvotes: 1

djjjuk
djjjuk

Reputation: 358

$ret = preg_match_all('/^([0-9]+\'|:)/', $str, $matches);
var_dump($ret) // 0 for no match, 1 for match

Upvotes: 0

Related Questions