cut text after (x) amount of characters

php, wordpress

Solution

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

Problem

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

Original source