Jak uzyskać pierwsze znaki x Z ciągu znaków, bez odcinania ostatniego słowa?

Mam następujący ciąg znaków w zmiennej.

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

Chcę pobrać pierwsze 28 znaków z powyższej linii, więc normalnie, jeśli użyję substr , to da mi Stack Overflow is as frictio to wyjście, ale chcę wyjść jako:

Stack Overflow is as...

Czy jest jakaś gotowa funkcja w PHP, aby to zrobić, lub proszę podać mi kod do tego w PHP?

Edited:

Chcę w sumie 28 znaków z ciągu bez łamania słowa, Jeśli zwróci mi kilka mniej znaków niż 28 bez złamania słowa, w porządku.

Author: Prashant, 2009-07-09

13 answers

Możesz użyć wordwrap() function, następnie eksploduj na nowej linii i weź pierwszą część:

$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';
 50
Author: Greg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-09 14:42:25

From AlfaSky :

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

    return $string;
}

Alternatywna, bardziej rozbudowana implementacja z bloga Elliotta Brueggemana :

/**
 * 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 search: "php trim ellipses")

 10
Author: John Kugelman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-09 14:42:16

Jest jeden sposób, aby to zrobić:

$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),' ')."...");
 3
Author: Mike Dinescu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-09 14:42:19

To najprostsze rozwiązanie, jakie znam...

substr($string,0,strrpos(substr($string,0,28),' ')).'...';
 2
Author: Travis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-09 14:45:52

To najprostszy sposób:

<?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
Author: PachinSV,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-08 20:14:05

Użyłbym string tokenizer aby podzielić łańcuch na słowa podobne do tego:

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

Wtedy możesz wyciągnąć poszczególne słowa W DOWOLNY SPOSÓB.


Edit: Greg ma o wiele lepszy i bardziej elegancki sposób robienia tego, co chcesz. Wybrałbym jego rozwiązanie wordwrap ().

 0
Author: scheibk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-09 14:45:01

Możesz użyć 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) . "...";

Zastrzeżenie: nie Przetestowałem go.

Dodatkowo, jeśli twój ciąg zawiera \n s, może zostać wcześniej złamany.

 0
Author: stefs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-09 14:48:27

Try:

$string='Stack Overflow 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?'...':'');
 0
Author: KM.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-09 15:01:56
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
Author: David Morrow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-22 17:18:34

Problemy mogą pojawić się, jeśli twój ciąg znaków ma znaczniki html, &nbsp i wiele spacji. Oto, czego używam, że dba o wszystko: {]}

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;
}

Użycie:

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

Użycie z html:

$string = '<div><p>My wife is jealous of stackoverflow</p></div>';
echo LimitText($string,20,1);
// My wife is jealous
 0
Author: David D,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-29 11:27:47

This ' s Working for Me Perfect

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

Dostosuje i złamie ostatnią spację bez przecinania słowa...

 0
Author: Hitesh Aghara,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-11 14:35:17

Dlaczego nie spróbować go eksplodować i zdobyć pierwsze 4 elementy tablicy?

 -1
Author: ghostdog74,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-09 14:41:54
substr("some string", 0, x);

Z podręcznika PHP

 -1
Author: mcandre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-09 14:42:23