2

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

1

4 Answers 4

16
preg_match_all('~\d+(?:\.\d+)?~', $string, $matches);
var_dump($matches[0]);
Sign up to request clarification or add additional context in comments.

3 Comments

@Ste: What about 30.5x.2? Is that a thing you want to support?
@Alix Axel: I don't think, but is possible replace .2 with 0.2 ?
@Ste: Sure you can replace it. Just do $string = preg_replace('(?<!\d)\.\d+', '0$0', $string); before you run the code above.
8
$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.

1 Comment

I think preg_match() would make more sense (and make the output array easier to parse) than preg_match_all() as there's only one occurence of the pattern in the subject string.
2
preg_match('/^(\d+)x(\d+)/', '30x120 (test desc here)', $result);

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

2 Comments

meh - posted near identically at the same time as @Kevin
It's often a question of seconds :p
1

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

Running code

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.