2010-07-28 20 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;";