我有一个文本(.txt)文件,其中包含如下文本:
5 General
-10 Time Limits
-20 Scheduled Maintenance Checks
-30 Reserved
-40 Reserved
-50 Unscheduled Maintenance checks
6 DIMENSIONS and AREAS
7 LIFTING and SHORING
-00 General
-10 Jacking
-20 Shoring
8 LEVELING and WEIGHING
-00 General
-10 Weighing and Balancing
-20 Leveling
9 TOWING and TAXIING
-00 General
-10 Towing
-20 Taxiing
我想用逗号替换每行中的第一个空格(我正在尝试将txt文件转换为csv,以准备将其导入到db中)。我开始使用strpos()
函数,但是无法理解下一步该做什么。
奖励任务:我还希望在每行的末尾添加半冒号。
编辑:添加了实际数据,而不是示例数据。
一个简单的带有限制的preg_replace将起作用:
$str = '5 Here is some text.';
echo preg_replace('/ /', ',', $str, 1);
// OUTPUT:
// 5,Here is some text.
带循环:
<?php
$str = array('5 Here is some text.', '5 Here is some text.','-10 Here is some text.','-20 Here is some text.','-30 Here is some text');
foreach ($str as $a) {
echo preg_replace('/ /', ',', $a, 1)."<br>";
}
// OUTPUT:
// 5,Here is some text.
// -10,Here is some text.
// -20,Here is some text.
// -30,Here is some text.
编辑您的新编辑:
$str = "5 General
-10 Time Limits
-20 Scheduled Maintenance Checks
-30 Reserved
-40 Reserved
-50 Unscheduled Maintenance checks
6 DIMENSIONS and AREAS
7 LIFTING and SHORING
-00 General
-10 Jacking
-20 Shoring
8 LEVELING and WEIGHING
-00 General
-10 Weighing and Balancing
-20 Leveling
9 TOWING and TAXIING
-00 General
-10 Towing
-20 Taxiing";
$array = explode(PHP_EOL, $str);
foreach ($array as $a) {
echo preg_replace('/ /', ',', $a, 1)."<br>";
}
// OUTPUT:
/*
5,General
-10,Time Limits
-20,Scheduled Maintenance Checks
-30,Reserved
-40,Reserved
-50,Unscheduled Maintenance checks
6,DIMENSIONS and AREAS
7,LIFTING and SHORING
-00,General
-10,Jacking
-20,Shoring
8,LEVELING and WEIGHING
-00,General
-10,Weighing and Balancing
-20,Leveling
9,TOWING and TAXIING
-00,General
-10,Towing
-20,Taxiing
*/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句