Gagarin
Gagarin

Reputation: 11

How to remove last character from every line of string using 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?

Upvotes: 1

Views: 704

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

One-line solution using file_get_contents and preg_replace functions:

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

The output:

hello

world

welcome

home

how

are

you

any

thing

else

Upvotes: 1

u_mulder
u_mulder

Reputation: 54841

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 />";
}

Upvotes: 1

Related Questions