我正在尝试从字符串数组中提取符合条件的子字符串。数组中的一些字符串只有一个限定子字符串,但其他字符串可能有更多。我需要构建一个包含所有这些所需值的平面数组。
以下是我当前的 Codeigniter 方法,但它不处理存在多个合格子字符串的情况。
public function generatenewname()
{
$this->load->helper('directory');
$map = directory_map('./assets/file_upload/md/temp/', FALSE, TRUE);
for ($x = 0; $x < count($map); $x++) {
$newest[$x] = explode(" ", $map[$x]);
for ($y = 0; $y < count($newest[$x]); $y++) {
if (strlen($newest[$x][$y]) >= 7) {
$file[] = $newest[$x][$y];
}
}
}
for ($x = 0; $x < count($file); $x++) {
echo $x . ' ' . $file[$x] . '<br>';
}
}
假设我的 $map
数组包含以下内容:
$map = [
'BACK PACK BBP160800103 G086-1 8#.JPG',
'BACKPACK BBP160500010 G114-3#1.JPG',
'WSL160800024-WSL160800025 L83-5.JPG',
'IA041017 L83-5.JPG'
];
期望的结果:
[
'BBP160800103',
'BBP160500010',
'WSL160800024',
'WSL160800025',
'IA041017'
]
最佳答案
您可以根据起始键匹配模式。
$array = [
['BACK', 'PACK', 'BBP160800103', '', 'G086-1', '8#.JPG'],
['BACKPACK', 'BBP160500010', 'G114-3#1.JPG'],
['WSL160800024-WSL160800025', 'L83-5.JPG'],
['IA041017', 'L83-5.JPG']
];
$patterns = ['(BBP\w+)', '(WSL\w+)', '(IA\w+)'];
$codes = [];
$matcher = '/' . implode($patterns, '|') . '/';
foreach ($array as $arr) {
array_map(function ($value) use ($matcher, &$codes) {
preg_match_all($matcher, $value, $matches);
foreach($matches as $match) {
$codes = array_merge(array_filter($match), $codes);
}
}, $arr);
}
print_r(array_unique($codes));
// output
Array
(
[0] => IA041017
[2] => WSL160800024
[3] => WSL160800025
[6] => BBP160500010
[8] => BBP160800103
)
关于php - 从数组中的每个字符串中提取一个或多个符合条件的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44916815/