Reputation: 241
I get each time different string.
From the string i need to extract the version number. when the version number can come in different types like:
v1.3
V1.3
v 2.4.1
V 2.4.1
version1.3
version 1.3
Version2.4.1
Version 2.4.1
The output need to be: 1.3 or 2.4.1
one more problem is that string can contain numbers beside the version number.
what will be the fast way to do this task?
Upvotes: 2
Views: 3493
Reputation: 15141
<?php
ini_set("display_errors", 1);
$versions=array(
"v1.3",
"V1.3",
"v 2.4.1",
"V 2.4.1",
"version1.3",
"version 1.3",
"Version2.4.1",
"Version 2.4.1");
foreach($versions as $version)
{
preg_match("/[vV](?:ersion)?\s*\K[\d\.]+/", $version,$matches);
print_r($matches);
}
Output:
Array
(
[0] => 1.3
)
Array
(
[0] => 1.3
)
Array
(
[0] => 2.4.1
)
Array
(
[0] => 2.4.1
)
Array
(
[0] => 1.3
)
Array
(
[0] => 1.3
)
Array
(
[0] => 2.4.1
)
Array
(
[0] => 2.4.1
)
Upvotes: 1
Reputation: 2877
You can use preg_match
to do this. This will match any versions that are at the end of the string. Regex is /(\d+\.?)+$/
.
$versions = array(
'v1.3',
'V1.3',
'v 2.4.1',
'V 2.4.1',
'version1.3',
'version 1.3',
'Version2.4.1',
'Version 2.4.1',
);
foreach($versions as $version) {
if (0 !== preg_match('/(\d+\.?)+$/', $version, $matches)) {
echo 'original: ' . $version . '; extracted: ' . $matches[0] . PHP_EOL;
}
}
output
original: v1.3; extracted: 1.3
original: V1.3; extracted: 1.3
original: v 2.4.1; extracted: 2.4.1
original: V 2.4.1; extracted: 2.4.1
original: version1.3; extracted: 1.3
original: version 1.3; extracted: 1.3
original: Version2.4.1; extracted: 2.4.1
original: Version 2.4.1; extracted: 2.4.1
Upvotes: 2
Reputation: 14321
I'd use regex for this:
Code:
<?php
function getVersion($str) {
preg_match("/(?:version|v)\s*((?:[0-9]+\.?)+)/i", $str, $matches);
return $matches[1];
}
print_r(getVersion("Version 2.4.1"));
?>
Regex101:
https://regex101.com/r/6WnQKt/3
Upvotes: 5