Ste
Ste

Reputation: 1520

PHP preg match - regular expression with float value

have this string:

$var = "30.5x120.8 (test desc here)";

I need to get out 30.5 and 120.8 with a regular expression.. any help?? Thx

Upvotes: 2

Views: 4909

Answers (4)

NikiC
NikiC

Reputation: 101936

preg_match_all('~\d+(?:\.\d+)?~', $string, $matches);
var_dump($matches[0]);

Upvotes: 16

alex
alex

Reputation: 490233

$var = "30x120 (test desc here)";
 
preg_match_all('/^(\d+)x(\d+)/', $var, $matches);
 
var_dump($matches)

Ideone.

Output

array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(6) "30x120"
  }
  [1]=>
  array(1) {
    [0]=>
    string(2) "30"
  }
  [2]=>
  array(1) {
    [0]=>
    string(3) "120"
  }
}

Update

also work for 17.5x17.5 ?

Here is one which will...

/^(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)/

Ideone.

Upvotes: 8

Kevin
Kevin

Reputation: 5694

The following should do the trick: /^(\d+)x(\d+)/

Running code

Upvotes: 1

James C
James C

Reputation: 14149

preg_match('/^(\d+)x(\d+)/', '30x120 (test desc here)', $result);

and use $result[1] and $result[2]

Upvotes: 2

Related Questions