English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Whats wrong with this script? It's supposed to only echo the first 9 letters of the variable but echos the whole lot:

$string = 'hello one day i went';
function sub($string)
{
$Length = strlen($string);
if($Length > 9)
$string = substr($string, 0, 9) . "...";
return($string);
}
echo $string;
?>

It should echo just "hello one..."

2006-12-30 11:40:46 · 4 answers · asked by peter s 1 in Computers & Internet Programming & Design

4 answers

function truncateString($input, $maxlength) {
//set local variable to be input minus leading / trailing spaces
$out = trim($input);

//truncate strings longer than maxlength
if(strlen($out) > $maxlength) {
$out = substr($out, 0, $maxlength) . '...';
}

//return output
return $out;
}

//set local variable
$mystring = "hello one day i went";

//echo the return value of the truncateString function
echo truncateString($mystring, 9);
?>

2006-12-30 15:04:35 · answer #1 · answered by Anonymous · 0 1

You were close. I modified the code a little:
//Initializing $string
$string = 'hello one day i went';

//Function code is largely ignored if you don't "call" it
//Call it by evaluation as in below
//If you dont do that, the next line of code is executed
//which echos your variable
$string = LimitString($string);

//I moved this line above the function
//This makes your code more readable
//Good practice is to keep your main line together
//Then Subroutines, then Functions
//Any code that is outside of your main line may be missed.
echo $string;

function LimitString($string)
{
$Length = strlen($string);
if($Length > 9)
{$string = substr($string, 0, 9) . "...";
return($string);
}
//You were missing the end bracket for the function
}
?>

2006-12-30 15:37:42 · answer #2 · answered by Jeffrey F 6 · 0 0

the suited suited syntax is: If this would not paintings, then something on your server isn't set up wisely. in case you do no longer understand what you're doing, you likely shouldn't do it. installation insecure or incorrectly set-up cyber web servers is an extremely undesirable element (TM).

2016-10-28 18:36:04 · answer #3 · answered by ? 4 · 0 0

You are printing the string without formatting it. To get the desired result, you need to put:

echo sub($string);

That should do it.

2006-12-30 11:48:24 · answer #4 · answered by Alex V 3 · 1 1

fedest.com, questions and answers