[英]Split an array with a regular expression
我想知道是否可以通過使用正則表達式截斷數組。
特別是我有一個像這樣的數組:
$array = array("AaBa","AaBb","AaBc","AaCa","AaCb","AaCc","AaDa"...);
我有這個字符串:
$str = "AC";
我想要從$array
的切片開始到最后一個匹配/AC/
的字符串(在示例中,索引為5的“ AaCc”):
$result = array("AaBa","AaBb","AaBc","AaCa","AaCb","AaCc");
我怎樣才能做到這一點? 我以為可以使用array_slice
,但是我不知道如何使用RegEx。
這是我的出價
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
參數,沒有任何作用。 我原本有一個與解決方案一起使用的不同方向,但決定保持其簡單性。 但是,下面是實現該$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++;
}
我認為最簡單的方法可能是使用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"
位我不太確定嗎?
假設增量數字索引從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,將給出一個
嚴格的標准:只能通過引用傳遞變量
並且如果找不到匹配項,仍將返回第一個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.