Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cut text after (x) amount of characters

Tags:

php

wordpress

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

like image 950
Carpy Avatar asked Apr 26 '10 21:04

Carpy


People also ask

How do you split the first 5 characters of a string?

You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

How do you short a string in PHP?

Cutting a string to a specified length is accomplished with the substr() function. For example, the following string variable, which we will cut to a maximum of 30 characters. $string = 'This string is too long and will be cut short.


1 Answers

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..."
like image 189
Ben Avatar answered Sep 18 '22 21:09

Ben