1

I want to get the version number for some string in php. Here is the sample code

<?php

    function getVersion($str) {
        preg_match("/.*((?:[0-9]+\.?)+)/i", $str, $matches);
        return $matches[1];
    }

    print_r(getVersion("ansitl1-isam-6.0 1.0 9.7.03 418614 +"));
    print_r(getVersion("ams-ef 9.6.06ef4 - 394867"));

?>

for input string ansitl1-isam-6.0 1.0 9.7.03 418614 + output should be 9.7.03 for input string ams-ef 9.6.06ef4 - 394867 output should be 9.6.06

How to achieve this?

7
  • 3
    Can you please let us know what you tried and what didn't worked? Commented Dec 4, 2019 at 10:06
  • I tried the below function getVersion($str) { preg_match("/.*((?:[0-9]+\.?)+)/i", $str, $matches); return $matches[1]; } Commented Dec 4, 2019 at 10:08
  • For pattern num.num.num preceded by a space try (?<= )\d+\.\d+\.\d+ Commented Dec 4, 2019 at 10:18
  • @bobble bubble Do we need to provide escape characters? I am getting error Unknown modifier '\\' Commented Dec 4, 2019 at 10:25
  • 1
    Oh you're using double quotes. Either use single quotes for pattern or double the backslash :) See this PHP demo Commented Dec 4, 2019 at 10:27

1 Answer 1

1

If the pattern is always num.num.num preceded by a space.

(?<= )\d+\.\d+\.\d+

See this demo at Regex101 or a PHP demo at tio.run

There is not much Regex magic used here, just a lookbehind to check, there is a space before.
Instead it can also be done by a caturing group and getting $out[1] like in this demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.