Как получить первые x символов из строки, не обрезая последнее слово? - PullRequest
13 голосов
/ 09 июля 2009

У меня есть следующая строка в переменной.

Stack Overflow is as frictionless and painless to use as we could make it.

Я хочу получить первые 28 символов из вышеприведенной строки, поэтому обычно, если я использую substr , это даст мне Stack Overflow is as frictio этот вывод, но я хочу выводить как:

Stack Overflow is as...

Есть ли в PHP какие-либо готовые функции для этого, или, пожалуйста, предоставьте мне код для этого в PHP?

Отредактировано:

Я хочу, чтобы в строке было всего 28 символов, не разбив слово, если получится несколько символов меньше, чем 28, не разбив слово, это нормально.

Ответы [ 13 ]

51 голосов
/ 09 июля 2009

Вы можете использовать функцию wordwrap(), затем взорваться на новой строке и взять первую часть:

$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';
10 голосов
/ 09 июля 2009

С AlfaSky :

function addEllipsis($string, $length, $end='…')
{
    if (strlen($string) > $length)
    {
        $length -= strlen($end);
        $string  = substr($string, 0, $length);
        $string .= $end;
    }

    return $string;
}

Альтернативная, более содержательная реализация из блога Эллиотта Брюггемана :

/**
 * trims text to a space then adds ellipses if desired
 * @param string $input text to trim
 * @param int $length in characters to trim to
 * @param bool $ellipses if ellipses (...) are to be added
 * @param bool $strip_html if html tags are to be stripped
 * @return string 
 */
function trim_text($input, $length, $ellipses = true, $strip_html = true) {
    //strip tags, if desired
    if ($strip_html) {
        $input = strip_tags($input);
    }

    //no need to trim, already shorter than trim length
    if (strlen($input) <= $length) {
        return $input;
    }

    //find last space within length
    $last_space = strrpos(substr($input, 0, $length), ' ');
    $trimmed_text = substr($input, 0, $last_space);

    //add ellipses (...)
    if ($ellipses) {
        $trimmed_text .= '...';
    }

    return $trimmed_text;
}

(поиск в Google: "php trim ellipses")

3 голосов
/ 09 июля 2009

Вот один из способов сделать это:

$str = "Stack Overflow is as frictionless and painless to use as we could make it.";

$strMax = 28;
$strTrim = ((strlen($str) < $strMax-3) ? $str : substr($str, 0, $strMax-3)."...");

//or this way to trim to full words
$strFull = ((strlen($str) < $strMax-3) ? $str : strrpos(substr($str, 0, $strMax-3),' ')."...");
2 голосов
/ 09 мая 2012

Это самый простой способ:

<?php 
$title = "this is the title of my website!";
$number_of_characters = 15;
echo substr($title, 0, strrpos(substr($title, 0, $number_of_characters), " "));
?>
2 голосов
/ 09 июля 2009

Это самое простое из известных мне решений ...

substr($string,0,strrpos(substr($string,0,28),' ')).'...';
0 голосов
/ 11 августа 2016

Это работает для меня Идеально

function WordLimt($Keyword,$WordLimit){

    if (strlen($Keyword)<=$WordLimit) { return $Keyword; }
    $Keyword= substr($Keyword,0,strrpos(substr($Keyword,0,$WordLimit),' '));
    return $Keyword;
}

echo WordLimt($MyWords,28);

// OutPut : Stack Overflow is as

будет корректироваться и прерываться на последнем пробеле без вырезанного слова ...

0 голосов
/ 29 октября 2015

Проблемы могут возникнуть, если ваша строка имеет HTML-теги, & nbsp и несколько пробелов. Вот что я использую, чтобы позаботиться обо всем:

function LimitText($string,$limit,$remove_html=0){
    if ($remove_html==1){$string=strip_tags($string);}
    $newstring = preg_replace("/(?:\s|&nbsp;)+/"," ",$string, -1); // replace &nbsp with space
    $newstring = preg_replace(array('/\s{2,}/','/[\t\n]/'),' ',$newstring); // replace duplicate spaces
    if (strlen($newstring)<=$limit) { return $newstring; } // ensure length is more than $limit
    $newstring = substr($newstring,0,strrpos(substr($newstring,0,$limit),' '));
    return $newstring;
}

использование:

$string = 'My wife is jealous of stackoverflow';
echo LimitText($string,20);
// My wife is jealous

использование с html:

$string = '<div><p>My wife is jealous of stackoverflow</p></div>';
echo LimitText($string,20,1);
// My wife is jealous
0 голосов
/ 22 июня 2010
function truncate( $string, $limit, $break=" ", $pad="...") {

 // return with no change if string is shorter than $limit
 if(strlen($string) <= $limit){
    return $string;
 }

 $string = substr($string, 0, $limit);
 if(false !== ($breakpoint = strrpos($string, $break))){
    $string = substr($string, 0, $breakpoint);
 }
 return $string . $pad;
}
0 голосов
/ 09 июля 2009

вы можете использовать wordwrap .

string wordwrap  ( string $str  [, int $width= 75  [, string $break= "\n"  [, bool $cut= false  ]]] )

-

function firstNChars($str, $n) {
  return array_shift(explode("\n", wordwrap($str, $n)));
}

echo firstNChars("bla blah long string", 25) . "...";

отказ от ответственности: не проверял.

Кроме того, если ваша строка содержит \n s, она может быть повреждена раньше.

0 голосов
/ 09 июля 2009

Я бы использовал строковый токенизатор , чтобы разбить строку на слова, очень похожие на:

$string = "Stack Overflow is as frictionless and painless to use as we could make it.";
$tokenized_string = strtok($string, " ");

Тогда вы можете вытащить отдельные слова любым способом.


Редактировать: у Грега гораздо лучший и элегантный способ делать то, что вы хотите. Я бы пошел с его решением WordWrap ().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...