cyhcyhhychyc
cyhcyhhychyc

Reputation: 67

Can not match the last group of numbers using php preg_match()

preg_match_all("/(\d{12})
(?:,|$)/","111762396541,561572500056,561729950637,561135281443",$matches);

var_dump($mathes):

array (size=2)
  0 => 
    array (size=4)
      0 => string '561762396543,' (length=13)
      1 => string '561572500056,' (length=13)
      2 => string '561729950637,' (length=13)
      3 => string '561135281443' (length=12)
  1 => 
    array (size=4)
      0 => string '561762396543' (length=12)
      1 => string '561572500056' (length=12)
      2 => string '561729950637' (length=12)
      3 => string '561135281443' (length=12)

But I want the $matches like this:

array (size=4)
  0 => string '561762396543,' (length=13)
  1 => string '561572500056,' (length=13)
  2 => string '561729950637,' (length=13)
  3 => string '561135281443' (length=12)

I wanna match groups of numbers(each has 12 digits) and a suffix comma if there is one.The exeption is the last group of numbers,it doesnt have to match a comma,cause it reaches the end of the line.

Upvotes: 0

Views: 46

Answers (1)

jhilgeman
jhilgeman

Reputation: 1583

Try this instead:

preg_match_all("/(\d{12}(?:,|$))/","111762396541,561572500056,561729950637,561135281443",$matches);

When the $ is inside your character range brackets [ ] it is looking for the $ characters not the end-of-line.

EDIT: If you want to include the comma in your matches, then just use the above code sample and look at $matches[0].

If you wanted an easier syntax that matches any sort of word boundary, the \b will match commas and end-of-line, too: preg_match_all("/(\d{12}\b)/","111762396541,561572500056,561729950637,561135281443",$matches);

Upvotes: 1

Related Questions