限制 php 中的文本长度并提供“阅读更多”链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4258557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:25:30  来源:igfitidea点击:

limit text length in php and provide 'Read more' link

phptext

提问by Scorpion King

I have text stored in the php variable $text. This text can be 100 or 1000 or 10000 words. As currently implemented, my page extends based on the text, but if the text is too long the page looks ugly.

我将文本存储在 php 变量 $text 中。该文本可以是 100 或 1000 或 10000 个字。按照目前的实施,我的页面基于文本扩展,但如果文本太长,页面看起来很难看。

I want to get the length of the text and limit the number of characters to maybe 500, and if the text exceeds this limit I want to provide a link saying, "Read more." If the "Read More" link is clicked, it will show a pop with all the text in $text.

我想获取文本的长度并将字符数限制为 500,如果文本超过此限制,我想提供一个链接,上面写着“阅读更多”。如果单击“阅读更多”链接,它将显示一个包含 $text 中所有文本的弹出窗口。

回答by webbiedave

This is what I use:

这是我使用的:

// 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;

You can tweak it further but it gets the job done in production.

您可以进一步调整它,但它可以在生产中完成工作。

回答by Brian H

$num_words = 101;
$words = array();
$words = explode(" ", $original_string, $num_words);
$shown_string = "";

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

$shown_string = implode(" ", $words);

回答by Waqas Ahmed

I have combine two different answers:

我结合了两个不同的答案:

  1. Limit the characters
  2. Complete HTML missing tags

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

回答by CrazyMax

Simple use this to strip the text :

简单地使用它来剥离文本:

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

Edit and finally :

编辑,最后:

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;
}

Here separator is the href link to read more ;)

这里的分隔符是阅读更多内容的 href 链接;)

回答by Mohd Abdul Baquee

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

回答by bcosca

This method will not truncate a word in the middle.

此方法不会截断中间的单词。

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

回答by Alexandru Sirbu

Limit words in text:

限制文本中的单词:

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;
}

Limit chars in text:

限制文本中的字符:

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;
}

Use:

用:

$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);

回答by nekiala

There is an appropriate PHP function: substr_replace($text, $replacement, $start).

有一个合适的 PHP 函数: substr_replace($text, $replacement, $start).

For your case, because you already know all the possibilities of the text length (100, 1000 or 10000 words), you can simply use that PHP function like this:

对于您的情况,因为您已经知道文本长度的所有可能性(100、1000 或 10000 字),您可以简单地使用该 PHP 函数,如下所示:

echo substr_replace($your_text, "...", 20);

PHP will automatically return a 20 character only text with ....

PHP 将自动返回一个 20 个字符的文本,带有....

Se the documentation by clicking here.

单击此处查看文档

回答by Murtaza JAFARI

This worked for me.

这对我有用。

// 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;

Thanks @webbiedave

谢谢@webbiedave

回答by Er Parwinder Hirkewal

I Guess this will help you fix your problem please check under given Function : trims text to a space then adds ellipses if desired

我猜这将帮助您解决问题,请在给定的功能下检查:将文本修剪为空格,然后根据需要添加省略号

  • @param string $input text to trim

    • @param int $length in characters to trim to
    • @param bool $ellipses if ellipses (...) are to be added
    • @param bool $strip_html if html tags are to be stripped
    • @return string

      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;}
      
  • @param string $input 要修剪的文本

    • @param int $length 要修剪到的字符数
    • @param bool $ellipses 如果要添加省略号 (...)
    • @param bool $strip_html 如果要去除 html 标签
    • @return 字符串

      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;}