能否筛选数组中第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 returnstrue.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
相关产品推荐
相关产品推荐

