$versions = [
'1',
'1.0',
'1.001',
'1.0.1',
'1.00.1',
'1.0.01',
'10.0.1',
'10.01.10',
'1.0.0-beta',
'1.0.0-rc1',
'5.5.9-1ubuntu4.17',
'\'DROP DATABASE',
'1.2.3<script>xss</script>'
];
foreach ($versions as $version) {
if (preg_match('#^(\d+\.)?(\d+\.)?(\d+)(-[a-z0-9]+)?$#i', $version, $matches) !== 0) {
var_dump($matches[0]);
} else {
echo 'Could not find version number in string: ' . $version;
}
echo PHP_EOL;
}
Result:
string(1) "1"
string(3) "1.0"
string(5) "1.001"
string(5) "1.0.1"
string(6) "1.00.1"
string(6) "1.0.01"
string(6) "10.0.1"
string(8) "10.01.10"
string(10) "1.0.0-beta"
string(9) "1.0.0-rc1"
Could not find version number in string: 5.5.9-1ubuntu4.17
Could not find version number in string: 'DROP DATABASE
Could not find version number in string: 1.2.3<script>xss</script>
/^([0-9]+)\.([0-9]+)\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?$/?