1

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

GlennFriesen
  • 302
  • 4
  • 15

4 Answers4

2

What about something like this?

<title><?php echo substr( $mytitle, 0, 70 ); ?></title>
Andreas Hagen
  • 2,335
  • 2
  • 19
  • 34
  • 1
    Props for typing almost an identical answer 2 seconds before me. – Xeoncross May 08 '12 at 19:32
  • I tried this but it didn't work -- am I doing something wrong? <?php $string = <?=$header['title']?>; $string = substr($string, 0,20); echo "$string"; ?> – GlennFriesen May 08 '12 at 19:42
  • @GlennIsaac you are writing php inside the php... please just copy past the code shaed by Andreas by just replacing `$mytitle` with `$header['title']` – swapnilsarwe May 08 '12 at 19:46
  • WTF: `<?php echo substr($header['title'], 0, 70); ?>` Learn the basics pls. – MonkeyMonkey May 08 '12 at 19:46
  • forgive my short mental lapse, monkeymonkey -- *smacks head* -- you're totally right -- with that, I got it all working... i wonder though if there's a way to do this where the solution doesn't cut words that partially exceed the character limit of the full title. Truncation without any words cut in half -- that possible? – GlennFriesen May 08 '12 at 19:50
  • asked in another thread http://stackoverflow.com/questions/10505576/limiting-the-character-count-of-the-title-in-php-without-splitting-words – GlennFriesen May 08 '12 at 19:57
1

This is what substr is often used for.

<title><?php print substr($title, 0, 70); ?></title>
Xeoncross
  • 55,620
  • 80
  • 262
  • 364
1

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); ?>
Jeroen
  • 13,056
  • 4
  • 42
  • 63
  • wait... does this solution ensure that words aren't cut if they partially exceed the character count? if so, that's awesome – GlennFriesen May 08 '12 at 19:48
1

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>
MonkeyMonkey
  • 826
  • 1
  • 6
  • 19