簡體   English   中英

如何用不同的字符替換字符串中的第一個空格?

[英]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,以准備將其導入到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
*/

您可以使用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM