PHP String (tam kelime sadece kısaltır)

10 Cevap php

Ben önce burada benzer bir soru sordu, ama ben bu küçük çimdik mümkün olup olmadığını bilmek gerekir. Ben 100 karakter bir dize kısaltmak ve $small = substr($big, 0, 100); bunu kullanmak istiyorum. Ancak, bu sadece ilk 100 karakter alır ve bir kelime ya da kırılır umrumda değil.

Bir dize ilk 100 karaktere kadar sürebilir ama bir kelime kırmak yok emin olmak için herhangi bir yolu var mı?

Örnek:

$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"

$small = some_function($big);

$small = "This is a sentence that has more than 100 characters in it, and I want to return a string of only"

PHP kullanarak bunu yapmanın bir yolu var mı?

10 Cevap

Eğer "boşlukla ayrılmış karakter dizisi" ... Kullanım gibi kelimeleri tanımlarsak strrpos() dizesindeki son yer bulmak için, sonucu Döşeme, o konuma kısaltın.

$pos=strpos($content, ' ', 200);
substr($content,0,$pos ); 

Bu size tüm gerekenler

Tabii. Kolay preg_match'in etrafında sarıcı yazmak için muhtemelen:

function limitString($string, $limit = 100) {
    // Return early if the string is already shorter than the limit
    if(strlen($string) < $limit) {return $string;}

    $regex = "/(.{1,$limit})\b/";
    preg_match($regex, $string, $matches);
    return $matches[1];
}

EDIT : DAİMA dizesindeki son karakteri olarak bir boşluk değil Güncelleme

Evet, var. Bu benim aa birkaç yıl önce farklı forumlarda bir kullanıcı ödünç, bu yüzden bunun için kredi alamaz bir işlevdir.

//truncate a string only at a whitespace (by nogdog)
function truncate($text, $length) {
   $length = abs((int)$length);
   if(strlen($text) > $length) {
      $text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
   }
   return($text);
}

Sadece preg_replace çağrısı için ikinci parametre olarak '\\1' kullanmak istemiyorsanız otomatik, elips ekler unutmayın.

Bu fonksiyon, mümkünse bir kelime sınırında "..." ekleyerek bir dize kısaltır. Döndürülen dize $len dahil olmak üzere maksimum uzunluğa sahip olacak "...".

function truncate($str, $len) {
  $tail = max(0, $len-10);
  $trunk = substr($str, 0, $tail);
  $trunk .= strrev(preg_replace('~^..+?[\s,:]\b|^...~', '...', strrev(substr($str, $tail, $len-$tail))));
  return $trunk;
}

Örnekler çıkışlar:

  • truncate("Thanks for contributing an answer to Stack Overflow!", 15)
    returns "Thanks for..."
  • truncate("To learn more, see our tips on writing great answers.", 15)
    returns "To learn more..." (comma also truncated)
  • truncate("Pseudopseudohypoparathyroidism", 15)
    returns "Pseudopseudo..."

Bu benim için çalışıyor, benim komut dosyası kullanmak

<?PHP
$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!";
$small = some_function($big);
echo $small;

function some_function($string){
     $string = substr($string,0,100);
     $string = substr($string,0,strrpos($string," "));
     return $string;
}
?>

iyi şanslar

İşte tam kelime ile sonunda Dotts ile harika bir çözümdür

function text_cut($text, $length = 200, $dots = true) {
    $text = trim(preg_replace('#[\s\n\r\t]{2,}#', ' ', $text));
    $text_temp = $text;
    while (substr($text, $length, 1) != " ") { $length++; if ($length > strlen($text)) { break; } }
    $text = substr($text, 0, $length);
    return $text . ( ( $dots == true && $text != '' && strlen($text_temp) > $length ) ? '...' : ''); 
}

Input: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Output: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip...

wordwrap formats string according to limit, seprates them with \n so we have lines smaller than 50, ords are not seprated explodes seprates string according to \n so we have array corresponding to lines list gathers first element.

listesi (kısa $) = ("\ n", wordwrap ($ ali, 50)) patlayabilir;

lütfen rep Evert, ben yorum veya temsilcisi olamaz beri.

Burada örnek run

php >  $ali = "ali veli krbin yz doksan esikesiksld sjkas laksjald lksjd asldkjadlkajsdlakjlksjdlkaj aslkdj alkdjs akdljsalkdj ";
php > listesi (kısa $) = ("\ n", wordwrap ($ ali, 50)) patlayabilir;
php > var_dump($short);
string(42) "ali veli krbin yz doksan esikesiksld sjkas"
php > $ali ='';
php > listesi (kısa $) = ("\ n", wordwrap ($ ali, 50)) patlayabilir;
php > var_dump($short);
string(0) ""

Bu benim için yaptı ...

//trim message to 100 characters, regardless of where it cuts off
$msgTrimmed = mb_substr($var,0,100);

//find the index of the last space in the trimmed message
$lastSpace = strrpos($msgTrimmed, ' ', 0);

//now trim the message at the last space so we don't cut it off in the middle of a word
echo mb_substr($msgTrimmed,0,$lastSpace)

İşte benim çözüm:

/**
 * get_words_until() Returns a string of delimited text parts up to a certain length
 * If the "words" are too long to limit, it just slices em up to the limit with an ellipsis "..."
 *
 * @param $paragraph - The text you want to Parse
 * @param $limit - The maximum character length, e.g. 160 chars for SMS
 * @param string $delimiter - Use ' ' for words and '. ' for sentences (abbreviation bug) :)
 * @param null $ellipsis - Use '...' or ' (more)' - Still respects character limit
 *
 * @return string
 */
function get_words_until($paragraph, $limit, $delimiter = ' ', $ellipsis = null)
{
    $parts = explode($delimiter, $paragraph);

    $preview = "";

    if ($ellipsis) {
        $limit = $limit - strlen($ellipsis);
    }

    foreach ($parts as $part) {
        $to_add = $part . $delimiter;
        if (strlen($preview . trim($to_add)) <= $limit) { // Can the part fit?
            $preview .= $to_add;
            continue;
        }
        if (!strlen($preview)) { // Is preview blank?
            $preview = substr($part, 0, $limit - 3) . '...'; // Forced ellipsis
            break;
        }
    }

    return trim($preview) . $ellipsis;
}

Sizin durumda (örnek) olacaktır:

$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"

$small = get_words_until($big, 100);