How to Limit the Length of the Title Tag using PHP

落爺英雄遲暮 提交于 2020-01-16 00:42:11

问题


I want to limit the character count of automatically generated page titles in php.

Can you come up with any php or jquery code that can do this for me, with me just entering the character count maximum I want in page titles (70 characters)?


回答1:


What about something like this?

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



回答2:


This is what substr is often used for.

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



回答3:


You can use this simple truncate() function:

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

}

For example, in your template files/wherever you enter the title tag:

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



回答4:


The previous answers were good, but please use multibyte substring:

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

Otherwise multibyte characters could be splitted.

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

usage:

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


来源:https://stackoverflow.com/questions/10505165/how-to-limit-the-length-of-the-title-tag-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!