我有一个字符串的格式:
$15?1?2/:1$16E/:2$17?6?7/:6$19E/:7$3E/
我想使用preg_split()将其分解为一个数组,但我似乎无法获得正则表达式的权利。具体来说,我想要得到一个数组,其中所有的数值都直接跟在$后面。
在这个例子中:
[0] => 15
[1] => 16
[2] => 17
[3] => 19
[4] => 3
如果有人能给我解释一下产生这个的正则表达式,那就太棒了。
分割与匹配所有
拆分和匹配是同一枚硬币的两面。你甚至不需要拆分:这将返回你正在寻找的确切数组(参见PHP演示)。
$regex = '~$Kd+~';
$count = preg_match_all($regex, $yourstring, $matches);
print_r($matches[0]);
Array
(
[0] => 15
[1] => 16
[2] => 17
[3] => 19
[4] => 3
)
-
$
匹配$
-
K
告诉引擎放弃与最终匹配匹配的内容,它返回 -
d+
匹配您的数字
等待解释。:)
或者
$preg = preg_match_all("/$(d+)/", $input, $output);
print_r($output[1]);
http://www.phpliveregex.com/p/5Rc 下面是一个非正则表达式的例子:
$string = '$15?1?2/:1$16E/:2$17?6?7/:6$19E/:7$3E/';
$array = array_map( function( $item ) {
return intval( $item );
}, array_filter( explode( '$', $string ) ) );
思路是将字符串扩展为$字符,然后映射该数组并使用interval()来获得整数值。
下面是捕获分隔符的preg_split()示例:
$string = '$15?1?2/:1$16E/:2$17?6?7/:6$19E/:7$3';
$array = preg_split( '/(?<=$)(d+)(?=D|$)/', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
/*
(?<=$) look behind to see if there is: '$'
( group and capture to 1:
d+ digits (0-9) (1 or more times (greedy))
) end of 1
(?=D|$) look ahead to see if there is: non-digit (all but 0-9) OR the end of the string
*/
在这篇文章的帮助下,一个有趣的方法从结果数组中获取每秒钟的值。
$array = array_intersect_key( $array, array_flip( range( 1, count( $array ), 2 ) ) );