Skip to content
Advertisement

Regex get all numbers before colon

I have the folling string:

$string = "16,1-5,22-27&22:1&4:3"

I want to get all numbers before the colon and return an array with them. So for the given string i would get the following:

array(22,4)

Advertisement

Answer

You can use this lookahead based regex in preg_match_all:

d+(?=:)

Code:

$str = "16,1-5,22-27&22:1&4:3"; 

preg_match_all('/d+(?=:)/', $str, $matches);
print_r($matches[0]);

RegEx Demo

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement