다음과 같은 텍스트가 포함 된 텍스트 (.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] 삭제
몇 마디 만하겠습니다