如何使用 PHP 限制标题标签的长度


How to Limit the Length of the Title Tag using PHP

我想限制 php 中自动生成的页面标题的字符数。

你能想出任何可以为我做到这一点的 php 或 jquery 代码吗,我只需在页面标题中输入我想要的字符数最大值(70 个字符)?

这样的事情呢?

<title><?php echo substr( $mytitle, 0, 70 ); ?></title>

这就是 substr 经常使用的用途。

<title><?php print substr($title, 0, 70); ?></title>

您可以使用这个简单的 truncate() 函数:

function truncate($text, $maxlength, $dots = true) {
    if(strlen($text) > $maxlength) {
        if ( $dots ) return substr($text, 0, ($maxlength - 4)) . ' ...';
        else return substr($text, 0, ($maxlength - 4));
    } else {
        return $text;
    }
}

例如,在模板文件中/输入标题标签的任何位置:

<title><?php echo truncate ($title, 70); ?>

之前的答案很好,但请使用多字节子字符串:

<title><?php echo mb_substr($title, 0, 75); ?></title>

否则,可以拆分多字节字符。

function shortenText($text, $maxlength = 70, $appendix = "...")
{
  if (mb_strlen($text) <= $maxlength) {
    return $text;
  }
  $text = mb_substr($text, 0, $maxlength - mb_strlen($appendix));
  $text .= $appendix;
  return $text;
}

用法:

<title><?php echo shortenText($title); ?></title>
// or
<title><?php echo shortenText($title, 50); ?></title>
// or 
<title><?php echo shortenText($title, 80, " [..]"); ?></title>