根据“分隔符”字符将PHP字符串分割成数组子字符串

3
我想要做的是将PHP字符串根据“分隔符”字符分成一组子字符串,并将它们分组到数组中。以*^%为分隔符的字符保留。所以如果我有一个字符串"*这是一些文本^是要被分隔的*基于哪里%分隔符字符^",它应该被分割并放置在以下数组中:
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" 
}

我完全不知道如何实现这个。有人知道怎么做吗?


你尝试过使用explode()函数吗? - Maximus2012
编程术语中,“分隔符”被称为“定界符”。 - Alex W
我写了一个自定义字符串分词器,因为我在工作中感到无聊和老了。https://gist.github.com/Sammitch/774677bb7e82e4c6e128 - Sammitch
1个回答

3

如果您不需要$matches[0],可以将其取消设置:

preg_match_all('/(\*[^*^%]+)|(\^[^*^%]+)|(%[^*^%]+)/', $string, $matches);
$matches = array_map('array_filter', $matches);

print_r($matches);
array_filter()函数从捕获组子数组中删除空值,以得到问题中显示的数组。

array_map('array_filter' 真的吗?为什么不用 unset 呢? - Casimir et Hippolyte
1
array_filter可以用来移除数组中的空元素,避免使用循环和多次unset操作。 - AbraCadaver
请在否定字符类中删除多余的转义。回答正确。 - mickmackusa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接