Usando la funzione wordwrap . Suddivide i testi in più righe in modo tale che la larghezza massima sia quella specificata, spezzando i confini delle parole. Dopo la divisione, prendi semplicemente la prima riga:
substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n"));
Una cosa che questo oneliner non gestisce è il caso in cui il testo stesso è più corto della larghezza desiderata. Per gestire questo caso limite, si dovrebbe fare qualcosa del tipo:
if (strlen($string) > $your_desired_width)
{
$string = wordwrap($string, $your_desired_width);
$string = substr($string, 0, strpos($string, "\n"));
}
La soluzione sopra ha il problema di tagliare prematuramente il testo se contiene una nuova riga prima del punto di taglio effettivo. Ecco una versione che risolve questo problema:
function tokenTruncate($string, $your_desired_width) {
$parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
$parts_count = count($parts);
$length = 0;
$last_part = 0;
for (; $last_part < $parts_count; ++$last_part) {
$length += strlen($parts[$last_part]);
if ($length > $your_desired_width) { break; }
}
return implode(array_slice($parts, 0, $last_part));
}
Inoltre, ecco la classe di test PHPUnit utilizzata per testare l'implementazione:
class TokenTruncateTest extends PHPUnit_Framework_TestCase {
public function testBasic() {
$this->assertEquals("1 3 5 7 9 ",
tokenTruncate("1 3 5 7 9 11 14", 10));
}
public function testEmptyString() {
$this->assertEquals("",
tokenTruncate("", 10));
}
public function testShortString() {
$this->assertEquals("1 3",
tokenTruncate("1 3", 10));
}
public function testStringTooLong() {
$this->assertEquals("",
tokenTruncate("toooooooooooolooooong", 10));
}
public function testContainingNewline() {
$this->assertEquals("1 3\n5 7 9 ",
tokenTruncate("1 3\n5 7 9 11 14", 10));
}
}
MODIFICARE :
I caratteri UTF8 speciali come 'à' non vengono gestiti. Aggiungi 'u' alla fine del REGEX per gestirlo:
$parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);