剪切文本后(x)的字符

问题描述:

量这是在WordPress的(不知道有差别)剪切文本后(x)的字符

PHP的该位输出文章标题

<?php echo $data['nameofpost']; ?> 

这是简单的文本,可以在任何地方长达100个字符。我想要的是,如果输出的字符超过20个长时间来显示'...'或根本没有。

由于

后您检查字符串长度strlen使用substr

$string = "This is a large text for demonstrations purposes"; 
if(strlen($string) > 20) $string = substr($string, 0, 20).'...'; 
echo $string; 

输出

"This is a large text..." 

if(count($data['nameofpost']) > 20) 
{ 
    echo(substr($data['nameofpost'], 0, 17)."..."); 
} 

对于$data['nameofpost']大于20个字符它将输出第一17个加上三个点...

+4

是的,但如果它的短,会输出什么。 – nc3b 2010-04-26 21:56:12

+0

其他综合征...我一直是这个的受害者;) – 2010-04-26 22:04:19

+1

我假设他会把其他人放在那里。 :p – 2010-04-26 22:11:47

<?php 
    function abbreviate($text, $max) { 
     if (strlen($text)<=$max) 
      return $text; 
     return substr($text, 0, $max-3).'...'; 
    } 
?> 

<?php echo htmlspecialchars(abbreviate($data['nameofpost'], 20)); ?> 

一个共同的改进是试图削减在词的结束的字符串:

 if (strlen($text)<=$max) 
      return $text; 
     $ix= strrpos($text, ' ', $max-2); 
     if ($ix===FALSE) 
      $text= substr($text, 0, $max-3); 
     else 
      $text= substr($text, 0, $ix); 
     return $text.'...'; 

如果您使用UTF-8字符串,则希望使用字符串ops的mb_multibyte版本更适当地计算字符。

另一种在单词结尾处关闭字符串的方法是使用正则表达式。这一个设置在100个字符,100个字符或就近休息一词切断:

function firstXChars($string, $chars = 100) 
{ 
    preg_match('/^.{0,' . $chars. '}(?:.*?)\b/iu', $string, $matches); 
    return $matches[0]; 
} 

在你的主题文件中使用这样的事情

尝试使用<div class="teaser-text"><?php the_content_limit(100, ''); ?></div>

然后在文件的functions.php,使用此

function the_content_limit($max_char, $more_link_text = '(more...)', $stripteaser = 0, $more_file = '') 
{ 

    $content = get_the_content($more_link_text, $stripteaser, $more_file); 
    $content = apply_filters('the_content', $content); 
    $content = str_replace(']]>', ']]&gt;', $content); 
    $content = strip_tags($content); 

    if (strlen($_GET['p']) > 0) 
{ 

     echo "<div>"; 
     echo $content; 
     echo "</div>"; 
    } 
    else if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char))) 
{ 

     $content = substr($content, 0, $espacio); 
     $content = $content; 
     echo "<div>"; 
     echo $content; 
     echo "..."; 
     echo "</div>"; 
    } 
    else { 
     echo "<div>"; 
     echo $content; 
     echo "</div>"; 
    } 
} 

好运:)