I’ve using a function from a recommendation on php.net and works very well.
My problem is that some words are cut off halfway, example:
The big black dog was eati… it should read
The big black dog was eating…
Does anybody know how to amend the code below so I will always get full words returned?
function short_name($str, $limit)
{
// Make sure a small or negative limit doesn't cause a negative length for substr().
if ($limit < 3)
{
$limit = 3;
}
// Now truncate the string if it is over the limit.
if (strlen($str) > $limit)
{
return substr($str, 0, $limit - 3) . '...';
}
else
{
return $str;
}
}
function short_name($str, $limit)
{
if ($limit < 3) $limit = 3;
if (strlen($str) > $limit) {
$str = substr($str, 0, strpos(wordwrap($str, $limit), "\
"));
}
return $str;
}
It uses the [fphp]wordwrap[/fphp] function to split the string into lines of a maximum given length, and then returns the first line (based on the solution here).
As I said before, the wordwrap function splits a string into lines based on a maximum length argument. If you look at the manual page, you’ll see that by default it won’t split the string mid-word. Once the string is broken into lines, we just use substr to return everything from the beginning of the string up to the first line-break (i.e just the first line) which gives you the result you want.
You can use the [fphp]rtrim[/fphp] function for that… you just need to supply a list of characters that you want removed from the end of the input string.
I’d probably split it into two lines at this point, just to improve readability and avoid the line length getting too long, but it’s a matter of preference rather than a hard and fast rule:
I’d probably split it into two lines at this point, just to improve readability and avoid the line length getting too long
Absolutely.
I’ve been having this problem with some other code I’ve been working with recently, lines getting to long, hard to read and not sure how to break things up into more digestible snippets. Again, some good information here fretburner still learning PHP thanks.
We’re passing the original value of $str into a function (or a series of functions) which modify that value. We then reassign this new value back to the original variable.
I’ll have to do a bit of testing and get used to this thanks.
The main reason I ask.
I have the below inside a foreach loop(minimised for viewing) though just realised the .= which is the concatenation assignment string operator, which basically joins together instead of override. Correct?
I do sometimes use .= to concatenate strings, although one problem is that it can be hard to spot if you miss out the period, and then your code doesn’t work as you expect.