我需要拆分以下
$str = 'min(5,6,7,88),email'
$str= 'min(5,6,7,88),!email,max(6,5),alpha_numeric,required'//other possibilities
所以它返回一个如下数组:
array(
[0]=>array(
[0]=>'min',
[1]=>array(5,6,7,88)
)
[1]=>array(
[0]=>'email'
)
)
这可能吗? btw email
和min
可能是真的,5
6
7
88
答案 0 :(得分:0)
我认为preg_match最适合这种特殊情况。但是,单独的preg_match无法根据需要格式化输出。
preg_match('/(\w+)\(([0-9,]+)\),(\w+)+/', $str, $values);
$output = array(
array($values[1], explode(',', $values[2])),
array($values[3]),
);
答案 1 :(得分:0)
鉴于以下内容:
$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);
}
呈现以下结果:
Array
(
[0] => Array
(
[0] => min
[1] => Array
(
[0] => 5
[1] => 6
[2] => 7
[3] => 88
)
)
[1] => Array
(
[0] => email
)
)
答案 2 :(得分:0)
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 />';
给出
array(2) {
[0]=>
array(2) {
[0]=>
string(3) "min"
[1]=>
string(10) "(5,6,7,88)"
}
[1]=>
array(1) {
[0]=>
string(5) "email"
}
}
和
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"
}
}