Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you cut off text after a certain amount of characters in PHP?

Tags:

I have two string that i want to limit to lets say the first 25 characters for example. Is there a way to cut off text after the 25th character and add a ... to the end of the string?

So '12345678901234567890abcdefg' would turn into '12345678901234567890abcde...' where 'fg' is cut off.

like image 924
jiexi Avatar asked Aug 06 '09 20:08

jiexi


People also ask

How do I cut a string after a specific character in PHP?

The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.

How do I limit text length in PHP?

Approach 2 (Using mb_strimwidth() function): The mb_strimwidth function is used to get truncated string with specified width. It takes as input the string and the required number of characters.

How can I remove last 5 characters from a string in PHP?

You can use the PHP substr_replace() function to remove the last character from a string in PHP. $string = "Hello TecAdmin!"; echo "Original string: " . $string .

How do you remove portion of a string before a certain character in PHP?

You can use strstr to do this. Show activity on this post. The explode is in fact a better answer, as the question was about removing the text before the string.


2 Answers

May I make a modification to pallan's code?

$truncated = (strlen($string) > 20) ? substr($string, 0, 20) . '...' : $string;

This doesn't add the '...' if it is shorter.

like image 93
Tyler Carter Avatar answered Oct 14 '22 09:10

Tyler Carter


To avoid cutting right in the middle of a word, you might want to try the wordwrap function ; something like this, I suppose, could do :

$str = "this is a long string that should be cut in the middle of the first 'that'";
$wrapped = wordwrap($str, 25);
var_dump($wrapped);

$lines = explode("\n", $wrapped);
var_dump($lines);

$new_str = $lines[0] . '...';
var_dump($new_str);

$wrapped will contain :

string 'this is a long string
that should be cut in the
middle of the first
'that'' (length=74)

The $lines array will be like :

array
  0 => string 'this is a long string' (length=21)
  1 => string 'that should be cut in the' (length=25)
  2 => string 'middle of the first' (length=19)
  3 => string ''that'' (length=6)

And, finally, your $new_string :

string 'this is a long string' (length=21)


With a substr, like this :

var_dump(substr($str, 0, 25) . '...');

You'd have gotten :

string 'this is a long string tha...' (length=28)

Which doesn't look that nice :-(


Still, have fun !

like image 30
Pascal MARTIN Avatar answered Oct 14 '22 11:10

Pascal MARTIN