pocockn
pocockn

Reputation: 2063

Understanding Regular Expression Truncating String

I have found a function online that truncates a string to a certain amount of characters. It uses preg_replace to find the end of a string so it doesn't cut off the string mid word.

I am having problems understanding the pattern and what exactly it is matching

return preg_replace('/\s+?(\S+)?$/', '', substr( $string, 0, $length ) ) . $tail;

I get that \s looks for white space and \S looks for non white space, but can't figure out exactly how it's working

Upvotes: 1

Views: 87

Answers (1)

Alex Netkachov
Alex Netkachov

Reputation: 13562

This regexp cuts the last incomplete (or complete) word in the string.

Let's say that the string is "The quick brown fox jumps over the lazy dog". And we cut the string to "The quick brown fox jumps ove". Then /\s+?(\S+)?$/ will match " over" and replace it with empty string.

So I have found a function online that truncates a string to a certain amount of characters. is not exactly true. It truncates a string to a some number of character less then a certain amount of characters. And obviously, if there is a very long word, it will unfortunately truncate it to empty string.

Upvotes: 2

Related Questions