我想做的是将一个PHP字符串拆分为一组子字符串,这些子字符串基于以这些子字符串开头的"分隔符"字符分组为数组。字符*
、^
和%
被保留为分隔符字符。因此,如果我有字符串"*Here's some text^that is meant*to be separated^based on where%the divider characters^are"
,它应该被拆分并放置在数组中,如下所示:
array(2) {
[0] => "*Here's some text"
[1] => "*to be separated"
}
array(3) {
[0] => "^that is meant"
[1] => "^based on where"
[2] => "^are"
}
array(1) {
[0] => "%the divider characters"
}
我完全迷上了这个。有人知道如何实现这一点吗?
您不需要$matches[0]
,所以如果您想要,请取消设置:
preg_match_all('/('*[^*^%]+)|('^[^*^%]+)|(%[^*^%]+)/', $string, $matches);
$matches = array_map('array_filter', $matches);
print_r($matches);
array_filter()
从捕获组子数组中删除空数组,以给出问题中所示的数组