【问题标题】:How can I limit an html texts with some character count?如何限制具有某些字符数的 html 文本?
【发布时间】:2016-06-17 05:53:39
【问题描述】:

我有一个 HTML 格式的博客文章内容。我只想在帖子列表中显示 25 个单词。

当我使用此代码时,由于标签关闭而出现一些错误。

function str_limit_word($text, $limit, $ending = '...') {
    if (str_word_count($text, 0) > $limit) {
        $words = str_word_count($text, 2);
        $pos = array_keys($words);
        $text = substr($text, 0, $pos[$limit]) . $ending;
    }
    return $text;
}

我该怎么做?

【问题讨论】:

  • 介意分享错误
  • <a href="http://ozankurt... </p> 等等
  • 请编辑您的问题并直言不讳
  • 在开始操作字符串之前使用$text = strip_tags($text);。这会从文本中删除 HTML,否则您很可能会返回无效的 HTML(加上一堆 25 个字符将是标签而不是文本)
  • 你需要创建一个dom部分并移除子元素或者不允许html

标签: php html


【解决方案1】:

在开始操作字符串之前使用$text = strip_tags($text);。这会从文本中删除 HTML,否则如果恰好截断标记中间的文本,您很可能会返回无效的 HTML,并且任何 HTML 属性也将计入字符串长度。

像这样:

function str_limit_word($text, $limit, $ending = '...') {
    // Remove any HTML tag in the string.
    $text = strip_tags($text); 

    if (str_word_count($text, 0) > $limit) {
        $words = str_word_count($text, 2);
        $pos = array_keys($words);
        $text = substr($text, 0, $pos[$limit]) . $ending;
    }
    return $text;
}

【讨论】:

    【解决方案2】:

    试试这个。

           function character_limiter($text, $limit, $start = 0) {
           if(strlen($text) > strlen($limit))
                return substr($text, $start, $limit) . '...';
            else 
                return $text;
          }
    

    【讨论】:

    • 不限制字数 ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多