Extract numbers after each occurrence of a substring

222 views Asked by At

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
2

There are 2 answers

0
mickmackusa On BEST ANSWER

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
1
Raxi On

Use preg_match_all and a pattern such as

if (preg_match_all('#\.id\.(\d+)\b#', $input, $matches, PREG_SET_ORDER)) {
    foreach ($matches as $match) {
        // $number = (int) $match[1];
        var_dump($match);
    }
}