Ответ 1
Вы можете использовать функцию wordwrap()
, затем взорваться на новой строке и перенести первую часть:
$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';
У меня есть следующая строка в переменной.
Qaru is as frictionless and painless to use as we could make it.
Я хочу получить первые 28 символов из вышеприведенной строки, поэтому обычно, если я использую substr, тогда он даст мне Qaru is as frictio
этот вывод, но я хочу, чтобы результат был следующим:
Qaru is as...
Есть ли какая-либо предварительная функция в PHP для этого, или, пожалуйста, предоставьте мне код для этого в PHP?
Отредактировано:
Я хочу, чтобы всего 28 символов из строки, не сломав слово, если оно вернет мне несколько меньше символов, чем 28, не сломав слово, это прекрасно.
Вы можете использовать функцию wordwrap()
, затем взорваться на новой строке и перенести первую часть:
$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';
От 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" )
Здесь один из способов:
$str = "Qaru 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),' ')."...");
Это самое простое решение, о котором я знаю...
substr($string,0,strrpos(substr($string,0,28),' ')).'...';
Это самый простой способ:
<?php
$title = "this is the title of my website!";
$number_of_characters = 15;
echo substr($title, 0, strrpos(substr($title, 0, $number_of_characters), " "));
?>
попробовать:
$string='Qaru is as frictionless and painless to use as we could make it.';
$n=28;
$break=strpos(wordwrap($string, $n,'<<||>>'),'<<||>>');
print substr($string,0,($break==0?strlen($string):$break)).(strlen($string)>$n?'...':'');
$string='Stack Overflow';
$n=28;
$break=strpos(wordwrap($string, $n,'<<||>>'),'<<||>>');
print substr($string,0,($break==0?strlen($string):$break)).(strlen($string)>$n?'...':'');
Я бы использовал строковый токенизатор, чтобы разбить строку на слова так:
$string = "Qaru is as frictionless and painless to use as we could make it.";
$tokenized_string = strtok($string, " ");
Затем вы можете вытащить отдельные слова так, как хотите.
Изменить: у Грега намного лучший и элегантный способ сделать то, что вы хотите. Я бы пошел с его решением wordwrap().
вы можете использовать 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, она может быть разорвана раньше.
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;
}
Проблемы могут возникнуть, если ваша строка содержит теги html, & nbsp и несколько пробелов. Вот что я использую, что заботится обо всем:
function LimitText($string,$limit,$remove_html=0){
if ($remove_html==1){$string=strip_tags($string);}
$newstring = preg_replace("/(?:\s| )+/"," ",$string, -1); // replace   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
Эта работа для меня Идеальная
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 : Qaru is as
он отрегулирует и разбивает последнее Пробел без вырезанного слова...
почему бы не попытаться взломать его и получить первые 4 элемента массива?
substr("some string", 0, x);