php - PHP将新行字符串存储到数组中
问题描述
我正在编写我的 PHP 脚本以使用explode 获取字符串,以便我可以将字符串存储到数组中。我的代码有问题,因为当我拆分字符串以将它们存储到数组中时,我会得到这样的结果:
Array ( [0] => [1] => 0.1 noname.gif [2] => 0.2 what-is-bootstrap.png )
应该是这样的:
Array ( [0] => 0.1 noname.gif [1] => 0.2 what-is-bootstrap.png)
以下是它在结果中显示的内容:
attid: 0.1 filename: noname.gif
attid: 0.2 filename: what-is-bootstrap.png
这是代码:
<?php
$attached = 'attid: 0.1 filename: noname.gif
attid: 0.2 filename: what-is-bootstrap.png';
$attached_files = explode('attid:', $attached);
$attached_files = str_replace('filename:', '', $attached_files);
?>
我不知道如何使用每个键(如 0 和 1)将字符串存储到数组中。
你能告诉我一个例子,当我拆分字符串时如何将字符串存储到数组中?
解决方案
如果添加以下行...
$attached_files = array_values(array_map('trim', array_filter($attached_files)));
它会做三件事。
将array_filter()
删除任何空行。第一个的原因是当你explode()
on 时'attid:'
,它会认为在第一次出现之前有一个值——它是空白的。您可以只array_shift()
删除第一项,但array_filter()
会过滤任何空行。
其次 - 你会发现有尾随的新行等。所以array_map()
withtrim
将确保删除任何多余的空格。
最后array_values()
将重新索引数组以从 0 开始。
推荐阅读
- azure - 如何使用 Azure 数据工厂复制活动提取电子邮件附件?
- python - 如何将包含键的字典和包含数据的列表中的数据保存为 csv 文件到各个键
- python - csv读取慢python的速度
- python - 找不到满足 pyimagesearch 要求的版本(来自版本:)找不到 pyimagesearch 的匹配分布
- python-3.x - 导入python模块时出错
- javascript - 如何在 Tabulator 中组合冻结列和可变表格高度?
- php - 未捕获的 DOMException:无法在“元素”上执行“setAttribute”:“1”不是 Laravel 刀片模板中的有效属性名称
- php - php foreach 中的 json 循环在 5 次通过后中断
- python - OpenCV:查找具有不同背景的对象的轮廓
- azure - 为可靠字典中的单个条目获取多个 Service Fabric 可靠字典通知