簡體   English   中英

試圖切斷最后一個空格的字符

[英]trying to cut off at the last character that's a space

我需要找出字符串中最后一個字符在哪里,字符是一個空格,然后在此處切斷它。 這是我正在使用的函數,但是if語句似乎出了點問題,但是我不知道是什么。 $ text-string中肯定有一個空格。

假設我有一個字符串“嘿,我叫喬”。 然后,必須將其縮寫為“嘿,我叫”。

$checkLastChar = false;
$text = $line[2];

while($checkLastChar != true){
   for($i = 1; $i <= strlen($text); $i++)
    {
        if($text[strlen($tekst) - $i] == " ") {
                $checkLastChar = true;
            $text = substr($text, 1, strlen($text) - $i);
        }
    }
}
substr($string, 0, strrpos($string, ' '));

為什么不使用rtrim()

更新

根據澄清, 像Nate的解決方案似乎更合適。

您是否考慮過使用trim() 它從開頭和結尾去除空格。

例:

echo trim(' Hello my name is Matt.  ');

嘗試這個:

<?php
$str = "dsajhc   \tsjdtgsd   "; // string with whitespaces
$str = preg_replace( '/(\s+.*)/i', '', $str ); // remove everything after whitespace
?>

希望能幫助到你。

暫無
暫無

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

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