首页 > 解决方案 > 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)将字符串存储到数组中。

你能告诉我一个例子,当我拆分字符串时如何将字符串存储到数组中?

标签: phparrays

解决方案


如果添加以下行...

$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 开始。


推荐阅读