php - 用逗号分解字符串,再用空格分解
问题描述
我有一串数字,如下所示:
$numbers = "one, two, three four, five";
我首先用逗号将其分解:
$numbers_array = explode(",", $numbers);
我的结果是:
array(4) {
[0] => string(3) "one"
[1] => string(4) " two"
[2] => string(11) " three four"
[3] => string(5) " five"
}
我的问题是,我怎样才能做到这一点?
array(5) {
[0] => string(3) "one"
[1] => string(4) "two"
[2] => string(6) "three"
[3] => string(5) "four"
[4] => string(5) "five"
}
解决方案
这应该将您的代码拆分为空格和逗号:
$numbers = "one, two, three four, five";
$numbers_array = preg_split("/[\s,]+/", $numbers);
然后,您可以通过执行以下操作删除空项目:
$filtered_numbers_array = array_filter($numbers_array);
推荐阅读
- javascript - 如何将递归 java 脚本逻辑转换为 typescript/angular
- javascript - 在反应中切换按钮时无法查看数据。没有错误
- database - 如何设计这个 NoSQL DB
- llvm - 使用 LLVM 通道混淆整数常量
- python - 查找两个数组之间变化值的索引
- python - 创建一个 Python 类,它既可以返回自身的表示,也可以使用计算结果调用
- matlab - MATLAB 图形通过旋转 3D 对象严重缩放
- android - 如何使用新的 android jetpack 导航保存底部导航视图片段的状态?
- aws-lambda - 为什么“dotnet lambda deploy-function”不能从 Azure DevOps 工件源中提取包?
- android - Android导航组件:java.lang.IllegalStateException:还原期间的未知目的地