Reputation:
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?
Upvotes: 0
Views: 656
Reputation: 7762
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
Upvotes: 0
Reputation: 13340
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.
Upvotes: 3
Reputation: 11
$str = "More than 16 characters of text in this string.";
print substr( $str,0, 16 );
Upvotes: 0
Reputation: 2854
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.
Upvotes: 4
Reputation: 2220
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 );
Upvotes: 0
Reputation: 3009
the function is called substr.
string substr ( string $string , int $start [, int $length ] )
so:
return substr($mystring,0,16);
should do it.
Upvotes: 8