如何用字符串替换不同字符的第一个空格?

时间:2014-12-25 03:33:03

标签: php

我有一个包含以下文字的文本(.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以准备导入数据库)。我开始使用strpos()功能,但无法理解下一步的操作。

奖金任务:我还希望每行末尾都有一个半冒号。

编辑:添加了实际数据而不是示例数据。

2 个答案:

答案 0 :(得分:4)

带限制的简单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
*/

答案 1 :(得分:1)

您可以使用str_pos()str_replace()

$csvData = array();
foreach (file("input.txt") as $line) {
    $spacePos = str_pos($line, ' ');
    $csvData[] = substr($line, 0, $spacePos) . ',' . substr($line, $spacePos + 1);
}

或者您可以转到更高级的preg_replace()来搜索和替换模式:

$csvData = array();
foreach (file("input.txt") as $line) {
    $csvData[] = preg_replace('/^([^ ]+) /', '\1,',  $line);
}