How to Limit the Length of the Title Tag using PHP

2019-08-02 21:59发布

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

标签: php seo title
4条回答
放荡不羁爱自由
2楼-- · 2019-08-02 22:34

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>
查看更多
Fickle 薄情
3楼-- · 2019-08-02 22:36

This is what substr is often used for.

<title><?php print substr($title, 0, 70); ?></title>
查看更多
Luminary・发光体
4楼-- · 2019-08-02 22:38

What about something like this?

<title><?php echo substr( $mytitle, 0, 70 ); ?></title>
查看更多
成全新的幸福
5楼-- · 2019-08-02 22:44

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); ?>
查看更多
登录 后发表回答