匹配数组子字符串第n个位置并显示此数组值的字符串

时间:2019-04-19 08:44:36

标签: php

如果我有一个字符串是

$str = "CD";

比 它只会在数组字符串下方找到第3和第4位,并获取该数组值,

$arr = ["ABCDE", "BCDEF", "BACDF","ACDLK"];

其输出如下所示,

$arr = ["ABCDE", "BACDF"];

有可能吗?

3 个答案:

答案 0 :(得分:1)

您可以使用strpos实现以下目标,

$arr    = ["ABCDE", "BCDEF", "BACDF", "ACDLK"];
$findme = "CD";
$result = [];
array_walk($arr, function ($mystring) use (&$result, $findme) {
    // check if string contains and its position index 0 means 1
    // and so on
    if (strpos($mystring, $findme) == 2) { 
        $result[] = $mystring;
    }
});
print_r($result);

输出

Array
(
    [0] => ABCDE
    [1] => BACDF
)

Demo

答案 1 :(得分:0)

我也尝试过

 $arr    = ["ABCDE", "BCDEF", "BACDF", "ACDLK"];
    $result = [];
    $search = "CD"; 
    function Search($search, $string){ 
        $position = stripos($string, $search, 2);   
        if ($position == true){ 
            return true; 
        } 
        else{ 
            return false; 
        } 
    } 
    foreach($arr as $key){
      if(Search($search, $key)){
         $result[] = $key;
        }
    } 
    print_r($result);

答案 2 :(得分:0)

使用strpos()时,请注意要查找的字符串不在要查找的位置之前的字符串中。

因此,CDCDE在寻找strpos()时将为CD给出0,因此可能会由于字符串位置不正确而拒绝该字符串。

一个简单的替代方法是使用substr()提取要检查的字符,并将其与之后的字符串进行比较。我已经对其进行了参数化,以便轻松更改...

$arr = ["ABCDE", "BCDEF", "BACDF", "ACDLK","ABDCDE", "CDCDE"];
$str = "CD";
$strLen = strlen($str);
$position = 2;
$result = [];
foreach( $arr as $string )  {
    if (substr($string, $position, $strLen) == $str) {
        $result[] = $string;
    }
};
print_r($result);

会给...

Array
(
    [0] => ABCDE
    [1] => BACDF
    [2] => CDCDE
)