jmasterx
jmasterx

Reputation: 54113

Can PHP exclude the newline character when reading line by line?

I want to read line by line but I do not want to deal with newline, I want it to be removed so I only end up with the content of the line.

So right now my function is:

function getProductCount($path)
{
   $count = 0;

foreach (file($path) as $name) {
    if($name == "<product>\n")
    {
       $count = $count + 1;
    }
}
       return $count;
}

But ideally I would want to do:

function getProductCount($path)
{
   $count = 0;

foreach (file($path) as $name) {
    if($name == "<product>")
    {
       $count = $count + 1;
    }
}
       return $count;
}

Is there a way to also remove carriage returns too?

Thanks

Upvotes: 2

Views: 9392

Answers (5)

Platinum Azure
Platinum Azure

Reputation: 46183

You can perform rtrim() on the line at the beginning of each loop iteration.

function getProductCount($path)
{
    $count = 0;

    foreach (file($path) as $raw_name) {
        $name = rtrim($raw_name);
        if($name == "<product>")
        {
            $count = $count + 1;
        }
    }
    return $count;
}

Upvotes: 4

Cystack
Cystack

Reputation: 3551

Either a regular expression (fetching the last occurence of \n in a line and stripping it) or simple $name = substr($name, 0, -2) would do the trick

Upvotes: -2

TRD
TRD

Reputation: 1027

http://www.php.net/manual/en/function.file.php

Look at the additional flags you can add to the function call. You should use "FILE_IGNORE_NEW_LINES"

Upvotes: 11

ain
ain

Reputation: 22749

Use trim() or rtrim()(if you want to preserve whitespaces in the beginning of the string) to strip whitespaces.

Upvotes: 0

marcelog
marcelog

Reputation: 7180

you might want to look at: http://php.net/trim and http://php.net/str_replace (so you can replace the eol by an empty character)

Upvotes: -1

Related Questions