2013-08-16 21 views
-1

目前我使用這個腳本:字符串切不能很好地工作

$tstring = strip_tags($nstitle); 
if (strlen($tstring) > 65) { 

    // truncate string 
    $stringCut = substr($tstring, 0, 65); 

    // make sure it ends in a word so assassinate doesn't become ass... 
    $tstring = substr($stringCut, 0, strrpos($stringCut, ' ')). 
       '.....<a href="">read more</a>'; 
} 

有時這並不正確,如果我輸入兩條線工作,並用這個切串。但是,它會給出不同的結果,例如,在每行不同長度的情況下獲取輸出。如果所有行相同或不同,我想要所有行的相同長度。

回答

1

除非添加填充,否則不能使每個輸入具有相同的長度(65)。由於你基本上是在最後一個空格之後切斷所有內容,所以最後一個空格可能出現在字符串中的不同位置。另外,如果沒有空間,您可能無法獲得預期的結果。所以1.檢查,2.墊。

// truncate string 
    $stringCut = substr($tstring, 0, 65); 
    //make sure it can find a space 
    if (strrpos($stringCut, ' ') > 0) { 
     $stringCut = substr($stringCut, 0, strrpos($stringCut, ' ')); 
    } 
    //then pad the string so its always 65 characters long 
    while (strlen($stringCut) < 65) { 
     $stringCut.="*"; 
    } 

// make sure it ends in a word so assassinate doesn't become ass... 
$tstring = $stringCut . '.....<a href="">read more</a>'; 
+0

@setn親愛的我拿出這個符號*爲什麼? – user2687922

+0

我喜歡顯示所有字符串相同的輸出。就像我在fb組列表中看到的所有具有長名字的組。但是所有的組名都被切割成等份:-) – user2687922

+0

也許用空白替換*。你指的是什麼組?提供一個鏈接。 – chiliNUT

相關問題