如何将字符串中的第一个空格替换为其他字符


How to replace the first blank space, within a string, with a different character?

我有一个文本(.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()函数,但无法弄清楚下一步该做什么。

奖励任务:我还希望在每行的末尾加一个分号。

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

一个简单的限制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
*/
您可以使用

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);
}