tags:

views:

298

answers:

8

im using php

if i have an uknown length of a string being outputted how can i limit it to only 16 characters to be outputted?

+6  A: 

the function is called substr.

string substr ( string $string , int $start [, int $length ] )

so:

return substr($mystring,0,16);

should do it.

tkotitan
A: 

Could you provide the code that you're using now? I'm going to go off the basis that you have a function returning a string of an unknown length. All you have to do is use the substr function.

$shorterString = substr( some_function(), 0, 16 );
nickohrn
A: 
substr($input_string, 0, 16)
SilentGhost
A: 

You can use substr function like this.

$text = "I am pretty long text.";
echo $text;                        //outputs I am pretty long text.
echo substr($text, 0, 16);         //outputs I am pretty long
Josef Sábl
A: 

use substr

 echo substr( $str,0, 16 )
paan
+3  A: 

The above methods, mentioning substr would help you. But, in case if your string contains multibyte characters (non-english characters), mb_substr should be used, which is a safe multi-byte substring function.

Alagu
A: 

$str = "More than 16 characters of text in this string.";

print substr( $str,0, 16 );

Fajita
+3  A: 

I personally like this one if it is a blog or something:

<?php

if(strlen($string) > 16) { 
echo substr($string,0,16) . "...";
}else{
echo $string;
}

?>

This way it won't truncate the string if its below 16 characters. Otherwise, it will add an ellipsis.

johnnietheblack