2013-07-06 96 views
2

我正在尋找一個解決方案的案例。 我有一個字符串如何在不切斷單詞的情況下在php中截斷字符串?

"This is a long string of words" 

我希望只使用第一幾句話,但如果我只是削減20字符之後的一切,它看起來就像這樣:

"This is a long strin" 

我能搶到前3字

implode(' ', array_slice(explode(' ', "This is a long string of words"), 0, 3)); 

但是在某些情況下,3個字將會太短「III」。

如何在第20個字符之前抓取儘可能多的單詞?

+0

您使用哪種語言? C++,Java,C#,Php? –

+0

哦,我沒有提到,php – user2331090

+1

您可以使用正則表達式,也可以搜索單詞之間的空格並使用split命令生成一組單詞。 –

回答

2

在我給你一個PHP的答案之前,你有沒有考慮過下面的CSS解決方案?

overflow:hidden; 
white-space:nowrap; 
text-overflow:ellipsis; 

這將導致文本在最合適的地方和標記截止省略號...被切斷。

如果這不是你要找的效果,試試這個PHP:

$words = explode(" ",$input); 
// if the first word is itself too long, like hippopotomonstrosesquipedaliophobia‎ 
// then just cut that word off at 20 characters 
if(strlen($words[0]) > 20) $output = substr($words[0],0,20); 
else { 
    $output = array_shift($words); 
    while(strlen($output." ".$words[0]) <= 20) { 
     $output .= " ".array_shift($words); 
    } 
} 
+0

您保存了我的日子 – user2331090

5

echo array_shift(explode("\n", wordwrap($text, 20)));

文檔:

+0

添加了一些文檔鏈接。 +1使用我忘記XD的功能 –