2012-05-08 33 views

回答

2

這樣的事情呢?

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

道具我面前打字幾乎相同的答案2秒。 – Xeoncross

+0

我試過這個,但它不起作用 - 我做錯了什麼? <?php $ string = <?= $ header ['title']?>; $ string = substr($ string,0,20); echo「$ string」; ?> GlennFriesen

+0

@GlennIsaac您正在編寫PHP內部的PHP ...請僅僅複製Andreas所描述的代碼,只需用'$ header ['title']替換'$ mytitle'' – swapnilsarwe

0

這就是substr經常用到的東西。

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

你可以使用這個簡單的截斷()函數:

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); ?> 
+0

等等......這個解決方案確保如果字數部分超過字符數,字不會被削減?如果是這樣,那真棒 – GlennFriesen

1

以前的答案是不錯,但請使用多字節子字符串:

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