Ограничить длину текста в php и предоставить ссылку "Читать дальше"
У меня есть текст, хранящийся в переменной php переменной $text. Этот текст может быть 100 или 1000 или 10000 слов. В настоящее время моя страница расширяется на основе текста, но если текст слишком длинный, страница выглядит уродливой.
Я хочу получить длину текста и ограничить количество символов, возможно, 500, и если текст превысит этот предел, я хочу предоставить ссылку с надписью "Подробнее". Если щелкнуть ссылку "Читать дальше", она отобразит всплывающее сообщение со всем текстом в текстовом формате.
Ответы
Ответ 1
Это то, что я использую:
// 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;
Вы можете настроить его дальше, но он выполняет работу на производстве.
Ответ 2
$num_words = 101;
$words = array();
$words = explode(" ", $original_string, $num_words);
$shown_string = "";
if(count($words) == 101){
$words[100] = " ... ";
}
$shown_string = implode(" ", $words);
Ответ 3
Я объединил два разных ответа:
- Ограничить символы
-
Завершите отсутствующие теги 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>"
Ответ 4
Просто используйте это, чтобы удалить текст:
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, чтобы прочитать больше;)
Ответ 5
<?php $string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry 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]
?>
Ответ 6
Этот метод не будет обрезать слово посередине.
list($output)=explode("\n",wordwrap(strip_tags($str),500),1);
echo $output. ' ... <a href="#">Read more</a>';
Ответ 7
Ограничить слова в тексте:
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);
Ответ 8
В принципе, вам нужно интегрировать ограничитель слов (например, что-то вроде этого) и использовать что-то вроде shadowbox. Ваша ссылка на ссылку будет ссылаться на PHP скрипт, который отображает всю статью. Просто установите Shadowbox на эти ссылки, и вы настроены. (См. Инструкции на своем сайте. Его легко.)
Ответ 9
Другой способ: вставьте в файл темы theme.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;
}
Вы можете использовать это.
Ответ 10
<?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 }}?>
Ответ 11
Я думаю, это поможет вам решить вашу проблему, пожалуйста, проверьте в соответствии с данной функцией: обрезает текст в пробел, а затем добавляет эллипсы, если это необходимо
Ответ 12
Вы можете плагин jQuery. Лично я бы сделал это с помощью jQuery и использовал плагин Expander. Вы можете скачать его здесь или просмотреть другие подобные плагины на сайте jQuery.