You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否筛选数组中第3、4位等于指定子串的元素?

Solution to Filter Array Elements by 3rd/4th Characters

Absolutely, you can easily achieve this using PHP's array_filter() function paired with substr() to check the target substring. Here's a straightforward implementation:

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

// Filter the array to match our criteria
$result = array_filter($arr, function($element) use ($str) {
    // Grab the 3rd and 4th characters (1-based index) → translates to 0-based index 2, length 2
    return substr($element, 2, 2) === $str;
});

// Optional: Reset array keys to start from 0 (removes original input keys)
$result = array_values($result);

print_r($result);

Output:

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

Breakdown of how it works:

  • array_filter() loops through each element in your array and retains only those elements where the callback function returns true.
  • substr($element, 2, 2) extracts the substring starting at 0-based index 2 (which is the 3rd character in 1-based counting) and grabs the next 2 characters (covering the 3rd and 4th positions you need).
  • The use ($str) clause lets us access the target string inside the anonymous callback function to compare against.
  • array_values() is optional but helpful if you want a clean, re-indexed array instead of keeping the original keys from the input array.

This method is efficient, readable, and directly meets your requirement of matching the specific substring positions.

内容的提问来源于stack exchange,提问作者p.Soni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:19:57