I am a novice when it comes to PHP.
I am using Wordpress with ACF (Advanced Custom Fields), so any data I get from a field I use the code below:
echo $fieldname;
One of these fields is for information about something, what I want to do is limit the amount of characters retrieved so that only 150 character are displayed.
Anyone have any idea how to do this?
You can do it with substr:
$str = "Aliquam odio eros, consectetur eu euismod faucibus, venenatis lobortis nulla. Pellentesque libero massa, bibendum in tempus ut, pretium et ante. In bibendum volutpat porta. ";
echo substr($str, 0, 150);
But if you have a long string, then you probaly want to cut it after an word. You can use the following function for this (it will cut of the str when it's to long and place the ...
behind it):
function truncate_string($str, $length) {
if (!(strlen($str) <= $length)) {
$str = substr($str, 0, strpos($str, ' ', $length)) . '...';
}
return $str;
}
You can also do it on the client side.
I don't know what you try to achieve, but if it's an title or something and you don't want it to be too long and ruin your layout then you can use CSS3 text-overflow
: jsFiddle example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With