I\'m trying to come up with the following function that truncates string to whole words (if possible, otherwise it should truncate to chars):
function Text_T
Have you considered using wordwrap? (http://us3.php.net/wordwrap)
Perhaps I can give you a happy morning after a long night of RegExp nightmares:
'~^(.{1,' . intval($limit) . '}(?<=\S)(?=\s)|.{'.intval($limit).'}).*~su'
Boiling it down:
^ # Start of String
( # begin capture group 1
.{1,x} # match 1 - x characters
(?<=\S)# lookbehind, match must end with non-whitespace
(?=\s) # lookahead, if the next char is whitespace, match
| # otherwise test this:
.{x} # got to x chars anyway.
) # end cap group
.* # match the rest of the string (since you were using replace)
You could always add the |$
to the end of (?=\s)
but since your code was already checking that the string length was longer than the $limit
, I didn't feel that case would be neccesary.