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)?
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)?
What about something like this?
<title><?php echo substr( $mytitle, 0, 70 ); ?></title>
This is what substr is often used for.
<title><?php print substr($title, 0, 70); ?></title>
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); ?>
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>