Отобразить выдержки из постов, ограниченные количеством слов - PullRequest
3 голосов
/ 24 января 2012

Я работаю над своим php-сайтом (не сайтом Wordpress) над основным индексом. Я отображаю два новейших поста.Дело в описании, которое показывает всю статью, в которой я нуждаюсь, чтобы отобразить выдержки из поста, возможно, ограничение в 35 слов.

<?=$line["m_description"]?>

<?
$qresult3 = mysql_query("SELECT * FROM t_users WHERE u_id=".$line["m_userid"]." LIMIT 1");
if (mysql_num_rows($qresult3)<1) { ?>

Ответы [ 2 ]

9 голосов
/ 24 января 2012
<?php

// just the excerpt
function first_n_words($text, $number_of_words) {
   // Where excerpts are concerned, HTML tends to behave
   // like the proverbial ogre in the china shop, so best to strip that
   $text = strip_tags($text);

   // \w[\w'-]* allows for any word character (a-zA-Z0-9_) and also contractions
   // and hyphenated words like 'range-finder' or "it's"
   // the /s flags means that . matches \n, so this can match multiple lines
   $text = preg_replace("/^\W*((\w[\w'-]*\b\W*){1,$number_of_words}).*/ms", '\\1', $text);

   // strip out newline characters from our excerpt
   return str_replace("\n", "", $text);
}

// excerpt plus link if shortened
function truncate_to_n_words($text, $number_of_words, $url, $readmore = 'read more') {
   $text = strip_tags($text);
   $excerpt = first_n_words($text, $number_of_words);
   // we can't just look at the length or try == because we strip carriage returns
   if( str_word_count($text) !== str_word_count($excerpt) ) {
      $excerpt .= '... <a href="'.$url.'">'.$readmore.'</a>';
   }
   return $excerpt;
}

$src = <<<EOF
   <b>My cool story</b>
   <p>Here it is. It's really cool. I like it. I like lots of stuff.</p>
   <p>I also like to read and write and carry on forever</p>
EOF;

echo first_n_words($src, 10);

echo "\n\n-----------------------------\n\n";

echo truncate_to_n_words($src, 10, 'http://www.google.com');

РЕДАКТИРОВАТЬ: Добавлен функциональный пример с учетом пунктуации и цифр в тексте

0 голосов
/ 24 января 2012

У меня есть функция, хотя другие люди могут сказать, что это нехорошо, потому что я все еще хорошо разбираюсь в PHP (советы приветствуют людей), но это даст вам то, что вы ищете, возможно, потребуется лучшее кодирование, если у кого-то есть предложения.

function Short($text, $length, $url, $more){
$short = mb_substr($text, 0, $length);

if($short != $text) {
    $lastspace = strrpos($short, ' ');
    $short = substr($short , 0, $lastspace);

    if(!$more){
        $more = "Read Full Post";
    } // end if more is blank

    $short .= "...[<a href='$url'>$more</a>]";
} // end if content != short

$short = str_replace("’","'", $short);
$short = stripslashes($short);
$short = nl2br($short);

} // end short function

Для использования:

говорят, что содержимое вашей статьи является переменной $ content

function($content, "35", "http://domain.com/article_post", "Read Full Story");
echo $short;

Аналогично, вы можете настроить функцию наудалите из него $ url и $ more и просто получите отрывок с ... в конце.

...