如何保持一定的数组值,多针php

时间:2013-12-25 12:40:14

标签: php arrays

这个有点棘手,我有一个数组,我需要在其中只保留一定的值字符串

$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

)

请注意我需要删除所需值之前和之后的所有内容

感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

如果您只需要字符串,那么您的问题是每个字符串 - 检查针数组中的某些内容是否在此字符串中 - 如果是,则返回第一个找到的针元素。 这可以通过以下方式轻松实现:

$file = [
    'i dont need this NEED1 i dont need this',
    'crap crap crap',
    'i dont need this NEED2 i dont need this',
    'garbage garbage garbage',
    'i dont need this WANT THIS ALSO i dont need this',
    'unused unused unused',
    'i dont need this ANDTHIS i dont need this',
];

$needle = ['NEED1', 'NEED2', 'WANT THIS ALSO','ANDTHIS'];
$result = [];
array_map(function($item) use ($needle, &$result)
{
   //regex creation may be done before iterating array - that will save resources
   if(preg_match('/'.join('|', array_map('preg_quote', $needle)).'/i', $item, $matches))
   {
      $result[] = $matches[0];
   }
}, $file);
//var_dump($result);

答案 1 :(得分:1)

$matches = [];
// don't really need array?
$getpositions = implode('', $getpositions);

foreach($searchpoz as $val){
    $pos = strpos($getpositions, $val);
    if($pos !== false) $matches[$val] = $pos;
}

// preserve order of occurrence.
asort($matches);
print_r(array_keys($matches));

: demo