【发布时间】:2013-12-26 01:35:37
【问题描述】:
这个有点棘手,我有一个数组,我只需要在其中保留某些值字符串
$getpositions = file("index.php");
$searchpoz = array('NEED1', 'NEED2', 'WANT THIS ALSO','ANDTHIS');
function strposa($haystack, $needles=array(), $offset=0) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle, $offset);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}//http://stackoverflow.com/a/9220624/594423
foreach($getpositions as $key => $clearlines) {
if(strposa($clearlines, $searchpoz) == false)
unset($getpositions[$key]);
}
$positionsorder = array_values($getpositions);
print_r($positionsorder);
Array
(
[0] => i dont need this NEED1 i dont need this
[1] => i dont need this NEED2 i dont need this
[2] => i dont need this WANT THIS ALSO i dont need this
[3] => i dont need this ANDTHIS i dont need this
)
所以想要的输出应该是
Array
(
[0] =>NEED1
[1] =>NEED2
[2] =>WANT THIS ALSO
[3] =>ANDTHIS
)
请注意,我需要删除所需值之前和之后的所有内容
感谢任何帮助,谢谢!
【问题讨论】:
-
请发布您的原始数组和所需的输出。现在我将您的问题视为 - 过滤 needle 数组,不包括那些在 original array 中找不到的项目
-
原始数组是一个 php 文件,它使用 file() 将所有行放入数组中,如上所示,我只保留了包含特定字符串的行,但我不需要完整的行,我只需要字符串
-
所以-再次-如果您只需要字符串,那么您的问题是针对每个字符串-检查 needle 数组中的某些内容是否在此字符串内-如果是,则返回首先找到 needle 元素。我说的对吗?
-
嗯,是的,我发现我在取消设置不需要的行后需要一个 else,并用匹配的针替换该值。说起来容易做起来难,但我就在上面