cut text after (x) amount of characters

2019-02-18 09:41发布

问题:

This is in wordpress (not sure that makes a difference)

This bit of php outputs the post title

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

It's simple text which can be anywhere up to 100 chars long. What i'd like is if the chars outputted are over 20 long to display '...' or simply nothing at all.

Thanks

回答1:

After you check the string length with strlen use substr

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

Outputs

"This is a large text..."


回答2:

Another way to cut the string off at the end of a word is with a regex. This one is set to cut off at 100 characters or the nearest word break after 100 characters:

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


回答3:

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

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

A common improvement would be to try to cut the string at the end of a word:

        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.'...';

If you are using UTF-8 strings you would want to use the mb_ multibyte versions of the string ops to count characters more appropriately.



回答4:

in your theme file use something like this try using <div class="teaser-text"><?php the_content_limit(100, ''); ?></div>

then in the functions.php files, use this

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>";
   }
}

good luck :)



回答5:

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

For $data['nameofpost'] greater then 20 chars it will output the first 17 plus three dots ....



标签: php wordpress