Search code examples
phpregexextractpreg-match-all

Extract numbers after each occurrence of a substring


My input:

$string = " text1 .id.123 .id.4576 text4 .id.56778 text 5 .id.76728";

How can I get output with php?

Extract number after .id.

Desired result:

123,4576,56778,76728

Solution

  • Match a literal dot, then id, then a literal dot, then reset the fullstring match with \K, then match one or more digits.

    Implode the matches with commas.

    Code: (Demo)

    $string = " text1 .id.123 .id.4576 text4 .id.56778 text 5 .id.76728";
    preg_match_all('~\.id\.\K\d+~', $string, $m);
    
    echo implode(',', $m[0]);
    // 123,4576,56778,76728