Merging two Regular Expressions to Truncate Words in Strings

后端 未结 2 1577
余生分开走
余生分开走 2021-01-18 01:54

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         


        
相关标签:
2条回答
  • 2021-01-18 02:38

    Have you considered using wordwrap? (http://us3.php.net/wordwrap)

    0 讨论(0)
  • 2021-01-18 02:51

    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.

    0 讨论(0)
提交回复
热议问题