Bir DB'den blog yazılarını çekiyorum. Ben 340 karakter maksimum uzunluğu metni kırpmak istiyorum.
Blog yazısı üzerinde 340 karakter ise ben son tam kelime metin düzeltme ve eklemek istiyorum '...' ucunda.
E.g.
NOT: In the begin....
BUT: In the ...
Diğer cevaplar metni roughly 340 karakter yapmak nasıl göstereceğim. Bu sizin için iyi ise, o zaman diğer yanıtlardan birini kullanın.
Ama isterseniz bir very strict maximum 340 karakter, diğer cevaplar çalışmaz. Sen '...' dize uzunluğunu artırabilir ekleyerek unutmamak gerekir ve bu hesaba almak gerekir.
$max_length = 340;
if (strlen($s) > $max_length)
{
$offset = ($max_length - 3) - strlen($s);
$s = substr($s, 0, strrpos($s, ' ', $offset)) . '...';
}
Not Ayrıca burada alır strrpos içinde aşırı kullanıyorum bir yerine ilk dizesi kısaltarak daha dize doğru konuma, doğrudan aramayı başlatmak için ofset.
ideone: Bu çalışma çevrimiçi görmek
fonksiyonu trim_characters ($ metin, $ uzunluk = 340) {
$length = (int) $length;
$text = trim( strip_tags( $text ) );
if ( strlen( $text ) > $length ) {
$text = substr( $text, 0, $length + 1 );
$words = preg_split( "/[\s]| /", $text, -1, PREG_SPLIT_NO_EMPTY );
preg_match( "/[\s]| /", $text, $lastchar, 0, $length );
if ( empty( $lastchar ) )
array_pop( $words );
$text = implode( ' ', $words );
}
return $text;
}
Use this function trim_characters() to trims a string of words to a specified number of characters, gracefully stopping at white spaces. I think this is helpful to you.
Ben bir yöntemde John Conde cevabı koydu:
function softTrim($text, $count, $wrapText='...'){
if(strlen($text)>$count){
preg_match('/^.{0,' . $count . '}(?:.*?)\b/siu', $text, $matches);
$text = $matches[0];
}else{
$wrapText = '';
}
return $text . $wrapText;
}
Örnekler:
echo softTrim("Lorem Ipsum is simply dummy text", 10);
/* Output: Lorem Ipsum... */
echo softTrim("Lorem Ipsum is simply dummy text", 33);
/* Output: Lorem Ipsum is simply dummy text */
echo softTrim("LoremIpsumissimplydummytext", 10);
/* Output: LoremIpsumissimplydummytext... */