ограничить длину текста в php и предоставить ссылку «Читать дальше»

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

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

Solutions Collecting From Web of "ограничить длину текста в php и предоставить ссылку «Читать дальше»"

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

// strip tags to avoid breaking any html $string = strip_tags($string); if (strlen($string) > 500) { // truncate string $stringCut = substr($string, 0, 500); // make sure it ends in a word so assassinate doesn't become ass... $string = substr($stringCut, 0, strrpos($stringCut, ' ')).'... <a href="/this/story">Read More</a>'; } echo $string; 

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

 $num_words = 101; $words = array(); $words = explode(" ", $original_string, $num_words); $shown_string = ""; if(count($words) == 101){ $words[100] = " ... "; } $shown_string = implode(" ", $words); 

Я объединил два разных ответа:

  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>" 

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

 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, чтобы прочитать больше;)

В принципе, вам нужно интегрировать ограничитель слов (например, что-то вроде этого ) и использовать что-то вроде shadowbox . Ваша ссылка на ссылку будет ссылаться на скрипт PHP, который отображает всю статью. Просто установите Shadowbox на эти ссылки, и вы настроены. (См. Инструкции на своем сайте. Это легко.)

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

 list($output)=explode("\n",wordwrap(strip_tags($str),500),1); echo $output. ' ... <a href="#">Read more</a>'; 

Другой способ: вставить в файл функции.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; } 

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

 <?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] ?> 
 <?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 }}?>