开发者

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开发者_如何学Python'//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


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]),
);


Given the following:

$test = "min(5,6,7,88),email";
$_ = null;
if (preg_match('/^(?<first>\w+)\((?<array>(?:[0-9]+\x2C*)+)\)\x2C(?<last>\w+)$/',$test,$_))
{
  $result = Array(
    Array($_['first'],explode(',',$_['array'])),
    Array($_['last'])
  );
  print_r($result);
}

Renders the following result:

Array
(
    [0] => Array
        (
            [0] => min
            [1] => Array
                (
                    [0] => 5
                    [1] => 6
                    [2] => 7
                    [3] => 88
                )

        )

    [1] => Array
        (
            [0] => email
        )

)


function parse($str) {
    $str = str_replace(array('(',')'),"0x00",$str);
    $strArray = explode("0x00",$str);
    $tokens = array();
    $tokenRef = 0;
    foreach($strArray as $tokenID => $tokenValue) {
        if (($tokenID % 2) == 1) {
            --$tokenRef;
            $tokens[$tokenRef++][1] = '('.$tokenValue.')';
        } else {
            $tokenList = explode(",",$tokenValue);
            foreach($tokenList as $token) {
                if ($token != '') {
                    $tokens[$tokenRef++][0] = $token;
                }
            }
        }
    }
    return $tokens;
}

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

$split = parse($str);

echo '<pre>';
var_dump($split);
echo '</pre>';
echo '<br />';

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

$split = parse($str);

echo '<pre>';
var_dump($split);
echo '</pre>';
echo '<br />';

Gives

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(3) "min"
    [1]=>
    string(10) "(5,6,7,88)"
  }
  [1]=>
  array(1) {
    [0]=>
    string(5) "email"
  }
}

and

array(5) {
  [0]=>
  array(2) {
    [0]=>
    string(3) "min"
    [1]=>
    string(10) "(5,6,7,88)"
  }
  [1]=>
  array(1) {
    [0]=>
    string(6) "!email"
  }
  [2]=>
  array(2) {
    [0]=>
    string(3) "max"
    [1]=>
    string(5) "(6,5)"
  }
  [3]=>
  array(1) {
    [0]=>
    string(13) "alpha_numeric"
  }
  [4]=>
  array(1) {
    [0]=>
    string(8) "required"
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜