简体   繁体   中英

Remove new lines from data retrived from text file using PHP

I have following data in text file

375020222511963
284970411563422
290245594366931

I need to retrieve a random variable from the above text file.

I use the following php code to do that

<?php 
    $file = file("file.txt");
    $len = count($file);
    $rand  = rand ( 0, $len-1 );
    echo $file[$rand];
?>

But it's returning new line along with the retrieved data. I need to retrieve data without new line.

The file() function has an optional second argument taking a bit mask of flags which affect what is returned in the array.

Available flags are FILE_USE_INCLUDE_PATH , FILE_IGNORE_NEW_LINES , and SKIP_EMPTY_LINES . The FILE_IGNORE_NEW_LINES is the one that you want to use in order to have each line in the array not include the trailing newline character.

So, your line of code should look like the following.

    $file = file("file.txt", FILE_IGNORE_NEW_LINES);

Descriptions and more info, see http://php.net/file .

Change last line to:

echo trim($file[$rand]);

trim() removes white-spaces (blanks, new lines, tabs) from the beginning and end of a string.

In order to avoid empty lines... If the last line is always the only empty one:

$rand = rand (0, $len - 2); // Instead of -1

Else, if you can have empty lines everywhere, replace the last two lines of code with:

do {
    $rand  = rand (0, $len - 1);
} while (trim($file[$rand]) == '');

echo $file[$rand];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM