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 (
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....
CODE
<?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');
?>
$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
CODE
$var .= '...';
is? Well, .= means $var = previous value of($var) + 'new string';
e.g:
CODE
$string = "hi";
$string .= ", hello";
echo $string; // Would return 'hi, hello'.
$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!
CODE
<?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');
?>
$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:
CODE
// $data ->foo; = variable. (text).
echo (strlen( $data ->foo ) > $max) ? substr($data ->foo, 0, $max).'...' : $data ->foo;
echo (strlen( $data ->foo ) > $max) ? substr($data ->foo, 0, $max).'...' : $data ->foo;