簡體   English   中英

如何使用php從字符串的每一行中刪除最后一個字符?

[英]How to remove last character from every line of string using php?

我想從單詞中刪除最后一個字符。 我有一個文件,上面寫着:

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

我正在嘗試刪除. 從每一行的末尾開始。 出於某種原因,我的代碼只從上次世界移除點else ,但離開其余不變。

這是我的代碼:

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

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

有誰知道我該如何解決?

你可以使用rtrim

rtrim —從字符串末尾去除空格(或其他字符)

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

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

那是因為每行的最后一個符號是換行符。 在做substr之前先trim一下:

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

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

或在file調用中添加第二個參數

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

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

使用file_get_contentspreg_replace函數的單行解決方案:

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

輸出:

hello

world

welcome

home

how

are

you

any

thing

else

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM