我想知道是否可以使用正则表达式截断数组。
特别是我有一个这样的数组:
$array = array("AaBa","AaBb","AaBc","AaCa","AaCb","AaCc","AaDa"...);
我有这个字符串:
$str = "AC";
我想要 $array
的切片,从匹配 /A.C./
的字符串开始到最后一次出现(在示例中,索引处的“AaCc” 5):
$result = array("AaBa","AaBb","AaBc","AaCa","AaCb","AaCc");
我该怎么做?我想我可以使用 array_slice
,但我不知道如何使用 RegEx。
最佳答案
这是 my bid
function split_by_contents($ary, $pattern){
if (!is_array($ary)) return FALSE; // brief error checking
// keep track of the last position we had a match, and the current
// position we're searching
$last = -1; $c = 0;
// iterate over the array
foreach ($ary as $k => $v){
// check for a pattern match
if (preg_match($pattern, $v)){
// we found a match, record it
$last = $c;
}
// increment place holder
$c++;
}
// if we found a match, return up until the last match
// if we didn't find one, return what was passed in
return $last != -1 ? array_slice($ary, 0, $last + 1) : $ary;
}
更新
我的原始答案有一个没有用的 $limit
参数。我最初确实有一个不同的方向,我打算使用解决方案,但决定保持简单。但是,下面是 version that implements that $limit
.所以……
function split_by_contents($ary, $pattern, $limit = 0){
// really simple error checking
if (!is_array($ary)) return FALSE;
// track the location of the last match, the index of the
// element we're on, and how many matches we have found
$last = -1; $c = 0; $matches = 0;
// iterate over all items (use foreach to keep key integrity)
foreach ($ary as $k => $v){
// text for a pattern match
if (preg_match($pattern, $v)){
// record the last position of a match
$last = $c;
// if there is a specified limit, capture up until
// $limit number of matches, then exit the loop
// and return what we have
if ($limit > 0 && ++$matches == $limit){
break;
}
}
// increment position counter
$c++;
}
关于php - 使用正则表达式拆分数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8900741/