【问题标题】:How to keep only certain array value, multiple needles php如何只保留某些数组值,多针php
【发布时间】: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,并用匹配的针替换该值。说起来容易做起来难,但我就在上面

标签: php arrays


【解决方案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

【讨论】:

  • @Benn 不过不需要这样 - 除非您将它用于其他用途? (在这种情况下 - 只需重命名变量......) - 这只是没有正则表达式的替代方案。
  • 是的,刚刚注意到,漂亮又短,似乎也更快
【解决方案2】:

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

$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);

【讨论】:

  • 伟大的一个,但 Emissarry 一个似乎更快,而不是 100%
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 2021-03-13
  • 2016-12-27
  • 1970-01-01
  • 2022-12-05
相关资源
最近更新 更多