How to get numeric data with dots inside a string?

There is a string variable containing numeric data with dots, for example $x = "OP/1.1.2/DIR"; . The position of the data number can change under any circumstances at the request of the user, changing it inside the application, and the slash panel can be changed by any other character; but dotted numbers are required. So, how to extract the data with a dotted line, here 1.1.2 , from the line?

0
source share
1 answer

Use regex :

 (\d+(?:\.\d+)*) 

Structure:

  • \d+ find one or more digits
  • \. literal decimal character .
  • \d+ followed by one or more digits.
  • (...)* this means 0 or more occurrences of this pattern match
  • (?:...) this tells the engine not to create a backlink for this group (basically we don’t use the link, so it’s pointless to have it)

You did not provide much information about the data, so I made the following assumptions:

  • Data will always contain at least one number
  • Data can only contain a number without a period
  • Data may contain multiple digits
  • The numbers themselves can contain any number of pairs of dots / numbers

If any of these assumptions is incorrect, you will have to change the regular expression.

Usage example:

 $x = "OP/1.1.2/DIR"; if (!preg_match('/(\d+(\.\d+)*)/', $x, $matches)) { // Could not find a matching number in the data - handle this appropriately } else { var_dump($matches[1]); // string(5) "1.1.2" } 
+4
source

All Articles