0

I wants to divide the string from text file.

if the .txt file has been read from some location. i wants to read the file and get strings in array.

Text file have following data

aaa  1111111,
    2hajakka,
    87uj5687,
     F2tryty   
bbb  45454545,
    rereer,
    87uj5687,
     4343343,
    944dsdds

I wants to store lines in array like

$arr = array(
"aaa 1111111, 2hajakka, 87uj5687, F2tryty ",
"bbb 45454545, rereer, 87uj5687, 4343343, 944dsdds");

notes:
data have starts first line as name, like(aaa,bbb) data's separated by commas. if comma not in the line it goes to next array field

Thanks in advance

1
  • your asking like 1-1 = 2 ( your expecting )!! how!!!!! its pos. Commented Mar 3, 2012 at 12:00

2 Answers 2

1

what you're trying to do is quite simple:

  1. collapse the multi-line records into a single line
  2. split the lines into an array

pretty much:

<?php
$string = 'aaa  1111111,
    2hajakka,
    87uj5687,
     F2tryty   
bbb  45454545,
    rereer,
    87uj5687,
     4343343,
    944dsdds';

// move lines beginning with a space to the previous line
$string = preg_replace('#\n +#', ' ', $string);
// split lines into array
$array = explode("\n", $string);
var_dump($array);
Sign up to request clarification or add additional context in comments.

4 Comments

thank u rodney but i have another doubt if i give empty spaces in data's like "1111 111, 2ha ja kka, 87 uj5 687, F 2try ty" how i use preg_replace
how exactly do these spaces behave?
like this rodney, J1.A1 DUT.A1 DUT.A2 C1.1 C2.1 , F2.1 F4.1 K1.1 , F2.1 F4.1 K1.1 , F2.1 F4.1 K1.1
urm, what? I have no clue what the meaning of 944dsdds is, I don't know if the space preceeding ` 4343343` has any relevance and if so, what it means. Nor do I know why rereer is one character shorter than the other keys (without a preceeding or trailing space). If all that has any meaning, please elaborate. Otherwise it just looks like badly formatted text.
0
$file_handle = fopen("myfile.txt", "r");
$arr[] = "";
$i = 0;
$temp_string = '';

while (!feof($file_handle)) {
$line = fgets($file_handle);
if(strpos($line,",")!== false)
{
$temp_string = $temp_string.$line;}
else{
$temp_string = $temp_string.$line;  
$arr[$i] = $temp_string;
$temp_string = '';
$i++;}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.