Question

How can I grab the entire contents of a line? I have a suspicion substr() is not the answer.

Authors: Mr. Foo, Mr. Bar
Date: Jan 1, 1970
etc...

In my $file_text string I have something similar to above. I'm looking for something like this:

$author_line = substr($file_text, 0, EOL);
Was it helpful?

Solution

Getting the file contents with file() automatically cuts it up into lines for you, if it helps.

Otherwise, try strstr($file_text,PHP_EOL,true)

OTHER TIPS

Grab each line with this:

$eachLine = explode( PHP_EOL, $file_text );

Then your normal substring will just grab everything. If it's all separated by colons like in your example, you could then explode to extract an key => value array of all the data in your string

// Grab each Line
$eachLine = explode( PHP_EOL, $file_text );
$data= array();

foreach($eachLine as $line) {

    $line = explode($line, ':');

    $data[trim($line[0])] = trim($line[1]);

}

This will give you a key => value array for all of the data in $data.

Get the first line (Replace end-of-line delimiter with your choice):

$author_line = strtok($file_text, "\n");

Alternative:

list($author_line) = explode("\n", $file_text, 1);
$author_line = substr($file_text, 0, strpos("\n"));

That will grab everything on the first line not including the end of line. You'll have to take into consideration \r\n on Windows vs. \n on Unix.

More properly coded as:

$author_line = substr($file_text, 0, strpos(PHP_EOL));

Try :

$lines = explode( PHP_EOL, $line_text );

Then loop over each line:

foreach( $lines as $line ) 
{
    //do something
}
$author_line = explode("\n", $file_text );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top