php - file_get_contents() 或类似函数

发布于 2024-12-12 03:32:20 字数 177 浏览 0 评论 0原文

我正在使用 file_get_contents() 检索我存储在 .txt 文件中的县列表。每个县都有自己的线路。

有没有办法在函数中的每个条目周围添加引号,然后在其后面添加逗号?我的一个限制是它必须在函数内填充,并且不能是两个单独的命令。

这可以做到吗?

或者也许我需要为此研究另一个函数?

I'm using file_get_contents() to retrieve a list of counties that I have stored in a .txt file. Each county is on its own line.

Is there a way to add quotations around each entry and then a comma following it within the function? One restriction I have is that it would have to populate within the function, and cannot be two separate commands.

Can this be done?

Or maybe I need to look into another function for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

孤独患者 2024-12-19 03:32:20
$countries = file('countries.txt'); // get country list into an array

$fixed_countries = array_map(function($v) { return '"' . trim($v) . '",'; }, $countries);
$countries = file('countries.txt'); // get country list into an array

$fixed_countries = array_map(function($v) { return '"' . trim($v) . '",'; }, $countries);
玻璃人 2024-12-19 03:32:20

你可以很容易地做到这一点,如果你使用 file 而不是 file_get_contents

$callback = create_function('$c', 'return "\"".trim($c)."\"";');
$countries = array_map($callback, file('countries.txt'));
return implode(', ', $countries);

我用对 PHP 有效的语法编写了 $callback $callback 5.3;也可以将其编写为匿名函数:

$callback = function($c) { return '"'.trim($c).'"'; };

查看实际操作

You can do it pretty easily, and it's even better if you use file instead of file_get_contents:

$callback = create_function('$c', 'return "\"".trim($c)."\"";');
$countries = array_map($callback, file('countries.txt'));
return implode(', ', $countries);

I have written $callback with a syntax that is valid for PHP < 5.3; it's also possible to write it as an anonymous function:

$callback = function($c) { return '"'.trim($c).'"'; };

See it in action.

眼波传意 2024-12-19 03:32:20

如果您逐行阅读某些内容,文件file_get_contents 更合适:

echo implode(',',
             array_map(function($county) {return '"' . trim($county) . '"';}),
                       file('counties.txt'));

If you read something line-by-line, file is more appropriate than file_get_contents:

echo implode(',',
             array_map(function($county) {return '"' . trim($county) . '"';}),
                       file('counties.txt'));
情深如许 2024-12-19 03:32:20

当然。

$countries = explode("\n",'"'.str_replace("\n","\",\n\"",file("countries.txt")));

这应该将文件像这样转换

country1
country2
...

成这样的数组:

array('"country1",','"country2",',...).

这就是你想要的,对吗?

Sure.

$countries = explode("\n",'"'.str_replace("\n","\",\n\"",file("countries.txt")));

That should convert the file like this:

country1
country2
...

into an array like this:

array('"country1",','"country2",',...).

That's what you want, right?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文