Regular expression to extract numbers from "200#5;300#10"

Asked

Viewed 400 times

3

What would be the best regular expression for the following entry "200#5;300#10" ?

  • 1

    It depends on what you want to select... You can explain better what you want to do?

  • The 200 means the total order and 5 the discount, the # is only the separator, ie first total, then # and then discount, and finally point and comma to separate from another condition.

1 answer

6


You’ll need two capture groups. Assuming it only has digits, you can use it like this:

/(\d+)#(\d+)/

The \d represents "digit", and the + means "one or more". Parentheses indicate catch groups, and the # indicates exactly the character #.

An example would be: http://ideone.com/wl3Q77

$string = "200#5;300#10";
preg_match_all('/(\d+)#(\d+)/', $string, $matches);
var_dump($matches);

// resultado: 
array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "200#5"
    [1]=>
    string(6) "300#10"
  }
  [1]=>
  array(2) {
    [0]=>
    string(3) "200"
    [1]=>
    string(3) "300"
  }
  [2]=>
  array(2) {
    [0]=>
    string(1) "5"
    [1]=>
    string(2) "10"
  }
}
  • 1

    Thanks Sergio! Thanks for the explanation!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.