Dexter Bengil
Dexter Bengil

Reputation: 6615

Regular Expression to match version number pattern

I want to match everything that looks like a version number on a string, so I started with this code

$str = 'ver=4.7.3/asdasd, ver=1, ver=2.5?, ver=4.7, ver=a124bcd12345';

preg_match_all("/ver=(\d+(\.\d{1,2}))/", $str, $output);

// $output
[
    "ver=4.7",
    "ver=2.5",
    "ver=4.7",
],
[
    "4.7",
    "2.5",
    "4.7",
],
[
    ".7",
    ".5",
    ".7",
],

With the result I got with $output[1] seems almost there but there is still missing, it should match these conditions:

1. should be a number - ok
2. n.n (4.7) - ok
3. n.n.n (4.7.1) - not being matched (it stops at 4.7)
4. 0.n - ok

But right now, instead of 4.7.3 it only returns 4.7.

I'm still a newbie with regular expressions so these things are still so horrible to me. Any help will be very much appreciated.

Upvotes: 2

Views: 561

Answers (2)

m87
m87

Reputation: 4523

You may perhaps use the following regex :

(?<=ver=)[\d.]+

see regex demo

PHP ( demo )

$str = 'ver=4.7.3/asdasd, ver=1, ver=2.5?, ver=4.7, ver=a124bcd12345';
preg_match_all('/(?<=ver=)[\d.]+/', $str, $output);
print_r($output);

Upvotes: 2

Sahil Gulati
Sahil Gulati

Reputation: 15141

Hope this will work.

Regex: ver=(\d+(\.\d){1,2})

Regex demo

Upvotes: 2

Related Questions