我有一個像preg_grep拿到指標,而不是價值
$arr = array("arif", "arin", "asif", "armin", "arpan");
數組我想尋找和得到滿足正則表達式中的元素的索引。 在這種情況下,我想要得到的指數0, 1, 3, 4
,因爲它們在陣列中我的模式
$regex = '|^ar|';
我有一個像preg_grep拿到指標,而不是價值
$arr = array("arif", "arin", "asif", "armin", "arpan");
數組我想尋找和得到滿足正則表達式中的元素的索引。 在這種情況下,我想要得到的指數0, 1, 3, 4
,因爲它們在陣列中我的模式
$regex = '|^ar|';
preg_grep()
使用爲:
<?php
$arr = array("arif", "arin", "asif", "armin", "arpan");
$regex = '|^ar|';
$res = array_keys(preg_grep($regex, $arr));
var_dump($res);
循環相匹配的每個項目,測試一下是否你的正則表達式使用preg_match
與項目匹配,如果這樣做,該指數添加到另一個索引數組。如果不匹配,請繼續。您將剩下一系列索引。而迭代通過輸入陣列
$words = array("arif", "arin", "asif", "armin", "arpan");
$pattern = '|^ar|';
$indices = array();
foreach ($words as $i => $word) {
// if there is a match
if (preg_match($pattern, $word)) {
// append the current index to the indices array
$indices[] = $i;
}
}
preg_match
功能:
$arr = array("arif", "arin", "asif", "armin", "arpan");
$keys = [];
foreach ($arr as $k => $item) {
if (preg_match('/^ar/', $item)) $keys[] = $k;
}
print_r($keys);
輸出:
Array
(
[0] => 0
[1] => 1
[2] => 3
[3] => 4
)
使用'preg_grep',然後'array_keys($ res ulting_arr)'([demo](https://ideone.com/5yS9ZX)) –