Главная > PHP > php: первые n слов из текста

php: первые n слов из текста

Ограничение на количество выводимых слов:

function limit_words($string, $word_limit) {
	$words=explode(" ",$string);
	return implode(" ",array_splice($words,0,$word_limit));
}

Ограничение по количество символов с сохранением слова, без обрезания:

function getPrewText($text,$maxwords=60,$maxchar=50) {
	//$text=strip_tags($text);
	$words=split(' ',$text);
	$text='';
	foreach ($words as $word) {
		if (mb_strlen($text.' '.$word)<$maxchar) {
			$text.=' '.$word;
		}
		else {
			$text.='...';
			break;
		}
	}
	return $text;
}

источники:
http://www.izero.ru/programmirovanie/ogranichenie-vyvoda-kolichestva-slov-v-predlozhenii-v-php.html
http://www.sablog.ru/php-ogranichenie-vyvoda-kolichestva-slov-v-predlozhenii/

Categories: PHP Tags:
  1. 28 июля,2018 в 14:45 | #1

    Спасибо, часто приходится использовать при разработке сайтов на PHP

  2. Дмитрий
    28 июня,2016 в 01:57 | #2
    function kd_get_substr($count=20, $str='', $is_point = true){
    	$str_arr = explode(" ",$str);
    	if(count($str_arr)&gt;=$count){
    		$out = '';
    		for($i=0;$i&lt;$count;$i++){
    			$out .= $str_arr[$i].&#039; &#039;;
    		}
    		if($is_point == true){
    			return trim($out).&#039; ...&#039;;
    		}else{
    			return trim($out);
    		}
    	}else{
    		return $str;
    	}
    }
  3. Герман
    3 февраля,2014 в 18:13 | #3

    Вот, немного допилил, чтоб работала как надо:

    function getPrewText($text,$maxwords=60,$maxchar=50) {
    	$text=strip_tags($text);
    	$words=split(' ',$text);
    	$text='';
    	$count = 0;
    	foreach ($words as $word) {
    		$count++;
    		if ($count &gt;= $maxwords) break;
    		if (mb_strlen($text.' '.$word)&lt;$maxchar) {
    			$text.=(($text != &#039;&#039;) ? &#039; &#039; : &#039;&#039;).$word;
    		} else {
    			break;
    		}
    	}
    	$text.=&#039;...&#039;;
    	return $text;
    }
  4. Николай
    4 октября,2013 в 13:58 | #4

    Спасибо помогло :)

  5. Илья
    1 октября,2012 в 17:11 | #5

    Спасибо!

Похожие публикации