Kelvin
Kelvin

Reputation: 903

PHP regex to extract special string

I am trying to use regex to extract a certain syntax, in my case something like "10.100" or "20.111", in which 2 numbers are separated by dot(.) . So if I provide "a 10.100", it will extract 10.100 from the string. If I provide "a 10.100 20.101", it will extract 10.100 and 20.101.

Until now I have tried to use

preg_match('/^.*([0-9]{1,2})[^\.]([0-9]{1,4}).*$/', $message, $array);

but still no luck. Please provide any suggestion because I don't have strong regex knowledge. Thanks.

Upvotes: 2

Views: 52

Answers (3)

Pedro Lobito
Pedro Lobito

Reputation: 99041

$decimals = "10.5 100.50 10.250";
preg_match_all('/\b[\d]{2}\.\d+\b/', $decimals, $output);
print_r($output);

Output:

Array
(
    [0] => 10.5
    [1] => 10.250
)

enter image description here

Regex Demo | Php Demo

Upvotes: 1

Sahil Gulati
Sahil Gulati

Reputation: 15141

Regex: /\d+(?:\.\d+)/

1. \d+ for matching digits one or more.

2. (?:\.\d+) for matching digits followed by . like .1234

Try this code snippet here

<?php

ini_set('display_errors', 1);
$string='a 10.100 20.101';
preg_match_all('/\d+(?:\.\d+)/', $string, $array);
print_r($array);

Output:

Array
(
    [0] => Array
        (
            [0] => 10.100
            [1] => 20.101
        )

)

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627488

You may use

\b[0-9]{1,2}\.[0-9]{1,4}\b

See the regex demo.

Details:

  • \b - a leading word boundary
  • [0-9]{1,2} - 1 or 2 digits
  • \. - a dot
  • [0-9]{1,4} - 1 to 4 digits
  • \b - a trailing word boundary.

If you do not care about the whole word option, just remove \b. Also, to match just 1 or more digits, you may use + instead of the limiting quantifiers. So, perhaps

[0-9]+\.[0-9]+

will also work for you.

See a PHP demo:

$re = '/[0-9]+\.[0-9]+/';
$str = 'I am trying to use regex to extract a certain syntax, in my case something like "10.100" or "20.111", in which 2 numbers are separated by dot(.) . So if I provide "a 10.100", it will extract 10.100 from the string. If I provide "a 10.100 20.101", it will extract 10.100 and 20.101.';
preg_match_all($re, $str, $matches);
print_r($matches[0]);

Output:

Array
(
    [0] => 10.100
    [1] => 20.111
    [2] => 10.100
    [3] => 10.100
    [4] => 10.100
    [5] => 20.101
    [6] => 10.100
    [7] => 20.101
)

Upvotes: 3

Related Questions