【问题标题】:Divide PHP string into arrayed substrings based on "divider" characters根据“分隔符”字符将 PHP 字符串划分为数组子字符串
【发布时间】:2015-06-06 14:01:22
【问题描述】:

我想做的是将 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" 
}

我完全迷失了这个。有谁知道如何实现这个?

【问题讨论】:

标签: php arrays regex string substring


【解决方案1】:

你不需要$matches[0],所以如果你想取消它:

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

print_r($matches);

array_filter() 从捕获组子数组中删除空,以给出问题中显示的数组

【讨论】:

  • array_map('array_filter' 真的吗?为什么不unset
  • array_filter 删除其他人的空洞。那将是一个循环和多个取消设置
  • 请删除否定字符类中多余的转义。很好的答案。
猜你喜欢
  • 1970-01-01
  • 2015-12-28
  • 2017-06-27
  • 1970-01-01
  • 2019-08-23
  • 2012-08-09
  • 2019-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多