简体   繁体   中英

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?

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

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

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

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