ограничить длину текста в php и предоставить ссылку «Подробнее» - PullRequest
41 голосов
/ 23 ноября 2010

У меня есть текст, хранящийся в переменной php $ text. Этот текст может быть 100 или 1000 или 10000 слов. В настоящее время моя страница расширяется на основе текста, но если текст слишком длинный, страница выглядит некрасиво.

Я хочу получить длину текста и ограничить количество символов, возможно, до 500, и если текст превышает этот предел, я хочу предоставить ссылку с надписью «Подробнее». Если щелкнуть ссылку «Подробнее», появится всплывающее окно со всем текстом в $ text.

Ответы [ 11 ]

135 голосов
/ 23 ноября 2010

Это то, что я использую:

// strip tags to avoid breaking any html
$string = strip_tags($string);
if (strlen($string) > 500) {

    // truncate string
    $stringCut = substr($string, 0, 500);
    $endPoint = strrpos($stringCut, ' ');

    //if the string doesn't contain any space then it will cut without word basis.
    $string = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);
    $string .= '... <a href="/this/story">Read More</a>';
}
echo $string;

Вы можете настроить его дальше, но оно выполнит работу на производстве.

9 голосов
/ 23 ноября 2010
$num_words = 101;
$words = array();
$words = explode(" ", $original_string, $num_words);
$shown_string = "";

if(count($words) == 101){
   $words[100] = " ... ";
}

$shown_string = implode(" ", $words);
3 голосов
/ 21 апреля 2016

У меня есть два разных ответа:

  1. Ограничение символов
  2. Полные отсутствующие теги HTML

    $string = strip_tags($strHTML);
    $yourText = $strHTML;
    if (strlen($string) > 350) {
        $stringCut = substr($post->body, 0, 350);
        $doc = new DOMDocument();
        $doc->loadHTML($stringCut);
        $yourText = $doc->saveHTML();
    }
    $yourText."...<a href=''>View More</a>"
    
2 голосов
/ 26 января 2015
<?php $string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";
if (strlen($string) > 25) {
$trimstring = substr($string, 0, 25). ' <a href="#">readmore...</a>';
} else {
$trimstring = $string;
}
echo $trimstring;
//Output : Lorem Ipsum is simply dum [readmore...][1]
?>
2 голосов
/ 23 ноября 2010

Просто используйте это, чтобы убрать текст:

echo strlen($string) >= 500 ? 
substr($string, 0, 490) . ' <a href="link/to/the/entire/text.htm">[Read more]</a>' : 
$string;

Редактировать и, наконец,

function split_words($string, $nb_caracs, $separator){
    $string = strip_tags(html_entity_decode($string));
    if( strlen($string) <= $nb_caracs ){
        $final_string = $string;
    } else {
        $final_string = "";
        $words = explode(" ", $string);
        foreach( $words as $value ){
            if( strlen($final_string . " " . $value) < $nb_caracs ){
                if( !empty($final_string) ) $final_string .= " ";
                $final_string .= $value;
            } else {
                break;
            }
        }
        $final_string .= $separator;
    }
    return $final_string;
}

Здесь разделитель - ссылка href, чтобы прочитать больше;)

1 голос
/ 31 января 2018

Ограничить количество слов в тексте:

function limitTextWords($content = false, $limit = false, $stripTags = false, $ellipsis = false) 
{
    if ($content && $limit) {
        $content = ($stripTags ? strip_tags($content) : $content);
        $content = explode(' ', $content, $limit+1);
        array_pop($content);
        if ($ellipsis) {
            array_push($content, '...');
        }
        $content = implode(' ', $content);
    }
    return $content;
}

Предельные символы в тексте:

function limitTextChars($content = false, $limit = false, $stripTags = false, $ellipsis = false) 
{
    if ($content && $limit) {
        $content  = ($stripTags ? strip_tags($content) : $content);
        $ellipsis = ($ellipsis ? "..." : $ellipsis);
        $content  = mb_strimwidth($content, 0, $limit, $ellipsis);
    }
    return $content;
}

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

$text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.";
echo limitTextWords($text, 5, true, true);
echo limitTextChars($text, 5, true, true);
1 голос
/ 23 ноября 2010

Этот метод не будет усекать слово в середине.

list($output)=explode("\n",wordwrap(strip_tags($str),500),1);
echo $output. ' ... <a href="#">Read more</a>';
0 голосов
/ 22 сентября 2018

Думаю, это поможет вам решить вашу проблему, пожалуйста, проверьте в соответствии с данной функцией: обрезает текст в пробел, а затем добавляет при желании эллипсы

  • @ строка параметра $ ввод текста для обрезки

    • @ param int $ длина символов для усечения до
    • @ param bool $ ellipses, если необходимо добавить эллипсы (...)
    • @ param bool $ strip_htmlесли html-теги должны быть удалены
    • @ возвращаемая строка

      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;}
      
0 голосов
/ 19 ноября 2014
<?php
     $images_path = 'uploads/adsimages/';
             $ads = mysql_query("select * from tbl_postads ORDER BY ads_id DESC limit 0,5 ");
                    if(mysql_num_rows($ads)>0)
                    {
                        while($ad = mysql_fetch_array($ads))

                        {?>


     <div style="float:left; width:100%; height:100px;">
    <div style="float:left; width:40%; height:100px;">
      <li><img src="<?php echo $images_path.$ad['ads_image']; ?>" width="100px" height="50px" alt="" /></li>
      </div>

       <div style="float:left; width:60%; height:100px;">
      <li style="margin-bottom:4%;"><?php echo substr($ad['ads_msg'],0,50);?><br/> <a href="index.php?page=listing&ads_id=<?php echo $_GET['ads_id'];?>">read more..</a></li>
      </div>

     </div> 

    <?php }}?>
0 голосов
/ 04 августа 2014

Другой метод: вставьте следующее в файл function.php вашей темы.

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_trim_excerpt');

function custom_trim_excerpt($text) { // Fakes an excerpt if needed
global $post;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$text = strip_tags($text);
$excerpt_length = x;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words) > $excerpt_length) {
array_pop($words);
array_push($words, '...');
$text = implode(' ', $words);
}
}
return $text;
}

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

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