2017-06-05 17 views
2

我有一個字符串,我想在一個50長的字符串的最後一個空白區域換新行。在x值中找到最後一個空字符串,並換行

<?php 
$str = "the condition that distinguishes animals and plants from inorganic matter, including the capacity for growth, reproduction, functional activity, and continual change preceding death."; 

$a = str_split($str, 50); 

foreach ($a as $value) { 
    $lastspace = strrpos($value, " "); 
    echo chunk_split($value, $lastspace, "<br>"); 
} 
?> 

預期結果:

,從無機物質,包括
容量爲生長,繁殖區分動物和
植物的條件下,官能
活性,並連續改變前死亡。

+1

,也許你可以使用這個正則表達式替換'(\ S)\ W * $' – kRicha

+0

告訴我一個例如/答案,所以我可以將其標記爲正確的。 – UZIERSKI

+1

結果會給你的字符串是什麼? – AbraCadaver

回答

4

它並不總是完美的(爲了更好的實現只是搜索wordwrap),但是這通常效果很好:

echo wordwrap($str, 50, '<br>'); 
相關問題