I do not think that this is the final version, I will try to supplement it later, but perhaps it will prompt you to solve this problem. My idea was to split the string into two substrings. In the second substring, find the first few words and add a triple point to them.
<?php $text = "Lorem ipsum dolor sit amet!! Consectetur?! Adipiscing elit... Nam tincidunt ultricies congue (turpis duis)."; $pre = substr($text, 0, 40); $after = substr($pre, 20, 40); $pattern = '/^((?:\S+\s+){2}\S+)/'; preg_match($pattern, $after, $matches); $k = strlen($matches[1])-1; $str = $matches[1]; while($k > 0 && !ctype_alpha($str[$k])) { $str = substr($str, 0, -1); $k--; } echo substr($pre, 0, 20),$str,'...';
The solution is quite working and can be used, but it is absolutely not perfect and needs some work.
UPDATE
I found a bug, like in my own and in other solutions on this page, the phrase with a hyphen of type test-test will always stop at the first test , if the function defines it as the last word, and the rest of the phrase is erased. Therefore, having played with regex, I found a more elegant pattern ( /^(\w+(-|\s?)\w+)/ ), which will find either the first two words in $after or one phrase divided by a hyphen like test-test Any signs specified after do not affect the result of the execution.
<?php $text = "Lorem ipsum dolor sit amet!! Consectetu-r?! Adipiscing elit... Nam tincidunt ultricies congue (turpis duis)."; $pre = substr($text, 0, 40); $after = substr($pre, 20, 40); $pattern = '/^(\w+(-|\s?)\w+)/'; preg_match($pattern, $after, $matches); $k = strlen($matches[1])-1; $str = $matches[1]; while($k > 0 && !ctype_alpha($str[$k])) { $str = substr($str, 0, -1); $k--; } echo substr($pre, 0, 20),$str,'...';
алгоритмprobably. - Flowneeerewould be better. Any programming language, of course. - user239133