Skip to content
Advertisement

How to use preg_match to match numbers between hyphens?

I need to validate strings like this:

$string = 'test3-10-2'; 

I need the penultimate number between hyphens, so in this case ’10’. These are other examples:

$string2 = 'test45-50-178-1';  //match = 178
$string3 = 'test45-580-89-12-1';  //match = 12

Can you help me?

Advertisement

Answer

this RegExp should do the trick using a positive lookahead: (change 4 to whatever max num of digits you want to allow)

d{1,4}(?=-d{1,4}$)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement