符合特定格式的数组中的截断字符串,然后过滤不变的元素
我有一个数组,它是我想要保留的弦和弦的混合物,我不想保留。在要保留的字符串中,我需要将它们从第一次发生的斜线中截断。
我的数组:
$code = [
'PO/2022/0001', // modify
'abc', // remove
'xyz', // remove
'PO2022/0001', // remove
'XY/2022/0002', // modify
'PO/2022/0232' // modify
];
我正在尝试爆炸
上面的数组中的字符串在/
上,如果新生成的数组具有3个元素,那么我需要将第一个值推入我的结果数组。
样本输入的预期结果:
['PO', 'XY', 'PO']
我能知道这样做的更好,有效的方法是什么?
这就是我到目前为止的:
foreach ($code as $v) {
$nwCode = explode("/",$v);
if(count($nwCode) == 3) {
$nwAry[] = $newCode[0];
}
$nwCode = [];
}
echo '<pre>',print_r ($nwAry).'</pre>';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
array_map
用于获得这些前缀,whilearray_filter
从无法比拟的项目中删除空的前缀。
您可以使用
array_reduce
也是如此。
The
array_map
used to get those prefixes, whilearray_filter
to remove the empty prefixes from the unmatching items.You could use
array_reduce
too.因为您想使用严格的格式/签名在字符串上执行替换,并过滤出与签名匹配的元素,因此PHP提供的最佳工具是
pregg_filter()
。模式分解:
代码:( demo )
输出:
如果您需要索引键,请致电
array_values(array_values()在结果数组中。
Because you want to perform replacements on strings with a strict format/signature AND filter out elements that do not match the signature, the best tool that PHP has to offer is
preg_filter()
.Pattern breakdown:
Code: (Demo)
Output:
IF you require indexed keys, call
array_values()
on the result array.