Cut text after (x) number of characters

This is in Wordpress (not sure if it matters)

This php bit outputs the header

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

      

It is simple text that can be up to 100 characters long. I would like the characters printed to be longer than 20 in order to display "..." or just nothing.

thanks

+2


a source to share


5 answers


After checking 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..."

      

+12


a source


Another way to cut a line at the end of a word is with a regular expression. This option is disabled with 100 characters or the closest word break after 100 characters:



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

      

+4


a source


<?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 general improvement would be to try and strip the line 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 like to use the mb_

multibyte version of the ops string to count more characters accordingly.

0


a source


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

then in 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 :)

0


a source


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

      

For $data['nameofpost']

more than 20 characters, it will output the first 17 plus three dots ...

.

-1


a source







All Articles