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.
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.
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.
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 .
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.
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.
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 !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With