2010-07-28 47 views
1

我有一定數量的字符,我可以適應現場我想要顯示的類別。所以我想知道是否有辦法限制這個函數可以輸出的字符數量。Php函數限制傳遞的字符數

我想限制這種功能輸出:

<?php the_category(', ') ?> 
outputs: WordPress, Computers, Blogging 

事情是這樣的:

<?php char_limit(the_category(', '), 14, '...') ?> 
outputs: WordPress, Com... 

我是新來的PHP和WordPress,所以如何執行將有助於痘痘的指導。

回答

4

webdestroya的意見和問題的重新認識使我建議substr_replace()

echo substr_replace(the_category(', '),"...",14); 

我原本建議word_wrap(),它不會截斷。

+1

這不正是他正在尋找......他並不想換弦,他想截斷它。 – 2010-07-28 22:37:49

+1

@webdestroya:對,我誤解了這個問題,修正了。 – 2010-07-28 22:50:19

+0

有沒有簡單的方法將wordpress函數the_category(',')更改爲字符串?因爲它沒有處理我通過的任何功能。 – ThomasReggi 2010-07-28 22:58:33

1

你可以使用一個字符串創建截斷功能

function truncate ($str, $length=10, $trailing='...') 
{ 
/* 
** $str -String to truncate 
** $length - length to truncate 
** $trailing - the trailing character, default: "..." 
*/ 
      // take off chars for the trailing 
      $length-=mb_strlen($trailing); 
      if (mb_strlen($str)> $length) 
      { 
         // string exceeded length, truncate and add trailing dots 
         return mb_substr($str,0,$length).$trailing; 
      } 
      else 
      { 
         // string was already short enough, return the string 
         $res = $str; 
      } 
  
      return $res; 
  
} 

得到它從here

0

這將讓你吧,用省略號

function shorten ($str, $len) 
{ 
    if (strlen($str) > $len) 
    { 
     return substr($str, 0, $len) . "..."; 
    else 
    { 
     return $str; 
    } 
} 
-1

您可能需要使用你的文章摘錄 - 有一個領域,你可以填寫和顯示的東西比第一個x字符更有意義

這裏是解釋摘錄就是一個鏈接: http://codex.wordpress.org/Excerpt

這裏是函數引用 http://codex.wordpress.org/Function_Reference/the_excerpt

基本上,你可以使用:<?php the_excerpt(); ?>

或在您的情況:

<?php if (is_category() || is_archive()) { 
    the_excerpt(); 
} else { 
    the_content(); 
} ?> 

你可以使用這個控制摘錄長度:

function new_excerpt_length($length) { 
    return 20; 
} 
add_filter('excerpt_length', 'new_excerpt_length'); 

如果你不想使用摘錄的想法,你仍然可以去老方法:

<?php 
$string = get_the_content(''); 
$newString = substr($string, 0, 20); 
echo $newString; 
?> 

希望這有助於:)

你也可以想看看插件

+0

我的問題是引用the_category()。它只顯示特定於該帖子的類別列表。不提及內容區域。 – ThomasReggi 2010-07-29 03:00:17

0

如果你看一下the_category是,它只是一個包裝函數:

function the_category($separator = '', $parents='', $post_id = false) { 
    echo get_the_category_list($separator, $parents, $post_id); 
} 

只要使用這樣的事情:

$catList = get_the_category_list(', '); 
if(strlen($catList)>14) 
    $catList = substr($catList,0,14) . "&#8230;";