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

时间:2010-11-23 16:50:23

标签: php text

我的文本存储在php变量$ text中。此文本可以是100或1000或10000个单词。正如目前实现的那样,我的页面基于文本扩展,但如果文本太长,页面看起来很难看。

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

13 个答案:

答案 0 :(得分:134)

这就是我使用的:

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

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

答案 1 :(得分:9)

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

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

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

答案 2 :(得分:3)

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

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

答案 3 :(得分:2)

简单地用它来剥离文本:

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链接,可以阅读更多内容;)

答案 4 :(得分:2)

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

答案 5 :(得分:1)

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

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

答案 6 :(得分:1)

限制文字中的字词:

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

答案 7 :(得分:1)

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

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

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

PHP会自动返回仅包含20个字符的文本,其中包含...

文档by clicking here.

答案 8 :(得分:0)

基本上,您需要整合字词限制器(例如something like this)并使用shadowbox之类的内容。您的阅读更多链接应链接到显示整篇文章的PHP脚本。只需在这些链接上设置Shadowbox即可。 (请参阅他们网站上的说明。很简单。)

答案 9 :(得分:0)

另一种方法:在主题的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;
}

你可以使用它。

答案 10 :(得分:0)

<?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 :(得分:0)

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

  • @param字符串$输入要修剪的文本

    • @param int $ length个要修剪的字符
    • @param bool $椭圆,如果要添加省略号(...)
    • @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;}
      

答案 12 :(得分:0)

这对我有用。

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

感谢@webbiedave