Search code examples
phpregexpreg-matchpreg-match-all

store numbers found in a string in a an array with preg_match


I need to detect the number of times numbers are found within a string. If the string is "1 ssdsdsd 2" I need an array with [1,2] in it. If the string is "1 a" I need an array such as: [1].

With my below attempts, I am close, but I end up with duplicate numbers in there. Preg match seems more appropriate for what I need but duplicates matches as well.

Any idea why this is? I appreciate any suggestions on how to accomplish this.

input

  preg_match_all("/([0-9]+)/", trim($s), $matches); //$s = "1 2", output below
  //preg_match("/([0-9]+)/", trim($s), $matches); //$s = "1 .", outputs [1,1]

output

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )
    [1] => Array
        (
            [0] => 1
            [1] => 2
        )
)

Solution

  • Remove the capture group,

    preg_match_all("/[0-9]+/", trim($s), $matches);
    

    The first element in matches array is the full match of the regex, the second one is the capture group.