php - Regex repeated group -


having trouble repeated capturing group:

(?:\[)(?:(?:\s*?)([2-9aqtkj][shcd])+?(?:\s*?)).*?(?:\]) 

see demo

basically want match card value (as, 8h etc..) combinations inside square brackets only

any appreciated.

thanks

you can use regex \g operator match multiple substrings inside [...]:

(?:\[|(?!^)\g)\s*\k[2-9aqtkj][shcd](?=[^\]]*]) 

see regex demo

in short, pcre regex match text that:

  • (?:\[|(?!^)\g)\s*\k - starts [ or @ end of previous successful match followed 0 or more whitespace symbols
  • [2-9aqtkj][shcd] - matches 2 characters each of defined sets
  • (?=[^\]]*]) - positive lookahead checking if there closing ] ahead of current position

php demo:

$re = '~(?:\[|(?!^)\g)\s*\k[2-9aqtkj][shcd](?=[^\]]*])~';  $str = "[as 4h 8s] [ 4h ] [as4h] [ 4h ";  preg_match_all($re, $str, $matches); print_r($matches[0]); 

Comments