我想知道是否可以使用正则表达式截断数组。
特别是我有一个像这样的数组:
$array = array("AaBa","AaBb","AaBc","AaCa","AaCb","AaCc","AaDa"...);
我有这个字符串:
$str = "AC";
我想从匹配$array
的字符串的开头到最后一次出现的/A.C./
切片(在样本中,索引为5的“AaCc”):
$result = array("AaBa","AaBb","AaBc","AaCa","AaCb","AaCc");
我该怎么做?我以为我可能会使用array_slice
,但我不知道如何使用RegEx。
答案 0 :(得分:4)
这是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++;
}
答案 1 :(得分:1)
我认为最简单的方法可能是使用foreach循环,然后对每个值使用正则表达式 - 虽然很高兴被证明是错误的!
一种替代方案可能是先破坏阵列......
$array = array("AaBa","AaBb","AaBc","AaCa","AaCb","AaCc","AaDa"...);
$string = implode('~~',$array);
//Some regex to split the string up as you want, guessing something like
// '!~~A.C.~~!' will match just what you want?
$result = explode('~~',$string);
如果你喜欢我可以做的正则表达式的一只手,那就不是100%正是你所要求的 - "A*C*"-->"AaCc"
位我不太确定吗?
答案 2 :(得分:1)
假设从0开始的增量数字索引
$array = array("AaBa","AaBb","AaBc","AaCa","AaCb","AaCc","AaDa");
$str = "AC";
$regexpSearch = '/^'.implode('.',str_split($str)).'.$/';
$slicedArray = array_slice($array,
0,
array_pop(array_keys(array_filter($array,
function($entry) use ($regexpSearch) {
return preg_match($regexpSearch,$entry);
}
)
)
)+1
);
var_dump($slicedArray);
PHP> = 5.3.0并将提供
严格的标准:只应通过引用传递变量
如果未找到匹配项,仍会返回第一个元素。