Reputation: 301
I have situation, where I have to echo certain length for several variables at various locations.
I know in bash we can use echo ${variable:0:20} to achieve this, without rewriting or refining the variable.
for example in php I want to be able to do this.
$string1 = "I am looking for a way to only echo the first 20 characters from a string variable";
echo $string:0:20;
I know it is dead simple to redefine my variable in php like this and echo it.
$small = substr($big, 0, 20);
echo $small;
But I have to use the same variable at some many location and each location I have to echo different length, so it is not feasible to use the above method. Is there is something else I am missing that I could use?
Upvotes: 0
Views: 11552
Reputation: 626
U can use this echo substr($string, 0, $length);
For more u can use this :
function output($string, $maxLen) {
echo substr($string, 0, $maxLen);
if(strlen($string) > $maxLen) echo ' ...';
}
Upvotes: 0
Reputation: 14425
I know in bash we can use echo ${variable:0:20} to achieve this, without rewriting or refining the variable.
In PHP you can use echo substr($variable, 0, 20);
also without rewriting or refining the variable.
For convenience (and easy modifications, e.g. adding ...
to all wrapped strings) you can wrap this in a small function:
function shorten($string, $maxLength) {
return substr($string, 0, $maxLength);
}
and use it as
echo shorten("Some very very very very very long string", 20);
Or even include the echo
in your function:
function output($string, $maxLength) {
echo substr($string, 0, $maxLength);
}
and use it as
output("Some very very very very very long string", 20);
Upvotes: 3
Reputation: 59297
You're not missing anything but the fact that you can just echo the returned value from substr
itself. If you want to go really short, like if writing the second parameter from substr
is too much, just wrap it in a new function.
function
ss($string, $size)
{
return substr($string, 0, $size);
}
echo ss('long ... string', 20);
Upvotes: 0
Reputation: 98961
The easiest solution is to build a function
so you can spare some lines of code, I don't see any other improvements you can make besides that, something like:
function small($string)
{
return substr($string, 0, 20);
}
Use it as:
print small("Some sentence longer than 20 chars");
Upvotes: 0