如何使用PHP删除每一行字符串中的最后一个字符?

I would like to remove last character from a word. I have a file with the words:

hello.
world
welcome.
home..
how.
are.
you
any
thing.
else.

I am trying to remove the . from the end of each line. For some reason my code removes the dot only from the last world else but leaves the rest as is.

Here is my code:

$words = file('words.txt');

foreach($words as $word) 
{
    echo substr($word, 0, -1);
    echo "<br />";
}

Does any one know how can i fix this?

That's because last symbol in each line is a linebreak. Do trim before doing substr:

$words = file('words.txt');

foreach($words as $word) 
{
    echo substr(trim($word), 0, -1);   // here we go
    echo "<br />";
}

Or add second argument to file call:

$words = file('words.txt', FILE_IGNORE_NEW_LINES);

foreach($words as $word) 
{
    echo substr($word, 0, -1);
    echo "<br />";
}

you can use rtrim

rtrim — Strip whitespace (or other characters) from the end of a string

$words = file('words.txt', FILE_IGNORE_NEW_LINES);

foreach($words as $word) 
{
   echo rtrim($word, '.');
    echo "<br />";
}

One-line solution using file_get_contents and preg_replace functions:

$new_contents = preg_replace("/(\w+)\.*([
]|$)/", "$1</br>", file_get_contents("words.txt"));
echo $new_contents;

The output:

hello

world

welcome

home

how

are

you

any

thing

else