Search code examples
phppreg-split

php preg_split split string conditionally


I need to split the following

$str = 'min(5,6,7,88),email'

$str= 'min(5,6,7,88),!email,max(6,5),alpha_numeric,required'//other possibilities

so it returns an array like so:

array(
  [0]=>array(
     [0]=>'min',
     [1]=>array(5,6,7,88)
  )
  [1]=>array(
     [0]=>'email'
  )
)

is this possible ? btw email and min could be anything really , aswell as 5 6 7 88


Solution

  • I think preg_match is best suited for this particular case. However, preg_match alone cannot format the output as you want it.

    preg_match('/(\w+)\(([0-9,]+)\),(\w+)+/', $str, $values);
    $output = array(
       array($values[1], explode(',', $values[2])),
       array($values[3]),
    );