This tutorial is a very simple one on cutting a string short,
During it, if you bother to read it and not just copy the code () you will learn how to determine the length of a string and how to take portions of strings.
I apoagise for not submitting any complicated tutorials but i am really too tired. So this is my lame attempt.
The functions used are....
strlen();
substr();
The final code:
Ok, lets get it out of the way....
<?php $text = "Hi my name is Matt"; function cutit ($var, $max) { $length = strlen( $var ); if($length > $max) { $var = substr($var, 0, $max); $var .= '...'; } return $var; } echo cutit($text, '4'); ?>
The write up
Heres what we are doing here in pseudocode within the function.
get string length
IF string length is greater than max length
> use substr to cut string length to max length
> add ... to the end of string
return the final value of new text.
The functions....
strlen is used to return the length of a string. strlen ( string )
substr returns a part of a string, where the start charactor and end charactor are set. substr ( string, (int) start, ([-]int) end )
You may just be wondering, as a final note what
$var .= '...';is?
Well, .= means $var = previous value of($var) + 'new string';
e.g:
$string = "hi"; $string .= ", hello"; echo $string; // Would return 'hi, hello'.
Final code....again
Here is some smaller code that does the same thing but with less lines for those who wish to save space lol!
<?php $text = "Hi my name is Matt"; function cutit ($var, $max) { return (strlen( $var ) > $max) ? substr($var, 0, $max).'...' : $var; } // Testing +Usage. echo cutit($text, '4'); ?>
Does the same thing
Oh course if you dont want this as a function because you only want it as a one off, try this:
// $data ->foo; = variable. (text). echo (strlen( $data ->foo ) > $max) ? substr($data ->foo, 0, $max).'...' : $data ->foo;