PHP string / word processing question

Let's say I have the following sentence:

A quick brown fox jumped over a lazy dog. 

However, I have a limit that only 25 characters are allowed in this sentence. This may leave me with something like:

 A quick brown fox jum 

However, this sentence does not make any grammatical sense, so I would prefer to find the last word that we can resolve by remaining in the press 25 char. This will give us something like:

 A quick brown fox 

which will be less than the 25 char limit, however it makes more grammatical meaning. I. The word is not broken, we have the maximum number of intelligible words, remaining within the limit.

How can I encode a function that will accept a string and a char limit such as 25, and if the string exceeds the limit, returns a string with the maximum number of words?

+6
string php
source share
3 answers

It is quite simple with regex:

 function first_few_words($text, $limit) { // grab one extra letter - it might be a space $text = substr($text, 0, $limit + 1); // take off non-word characters + part of word at end $text = preg_replace('/[^a-z0-9_\-]+[a-z0-9_\-]*\z/i', '', $text); return $text; } echo first_few_words("The quick brown fox jumps over the lazy dog", 25); 

Some additional features of this implementation:

  • Separates words in linebreaks and tabs.
  • Saves an extra word that ends with a 25.

Edit: the regular expression has been changed so that only letters, numbers, '_' and '-' are considered word characters.

+12
source share
 <?php function wordwrap_explode($str, $chars) { $code = '@@@'; return array_shift(explode($code, wordwrap($str, $chars, $code))); } echo wordwrap_explode('A quick brown fox jumped over a lazy dog.', 25); ?> 

Output:

 A quick brown fox jumped 
+2
source share

You cannot try to adapt this feature. I took the idea from the php website and adapted it to my needs. It takes the "head" and "tail" of the string and reduces the string (given the words) to a given length. For your needs, it may be good to separate the entire tail of the function.

 function strMiddleReduceWordSensitive ($string, $max = 50, $rep = ' [...] ') { $string=nl2space(utf8decode($string)); $strlen = mb_strlen ($string); if ($strlen <= $max) return $string; $lengthtokeep = $max - mb_strlen($rep); $start = 0; $end = 0; if (($lengthtokeep % 2) == 0) { $length = $lengthtokeep / 2; $end = $start; } else { $length = intval($lengthtokeep / 2); $end = $start + 1; } $tempHead = mb_strcut($string, 0, $length); $headEnd = strrpos($tempHead, ' ')+1; $head = trim(mb_strcut($tempHead, 0, $headEnd)); $tempTail = mb_strcut($string, -$length); $tailStart = strpos($tempTail, ' ')+1; $tail = trim(mb_strcut($tempTail, $tailStart)); //p($head); //p($tail); return $head . $rep . $tail; 

}

0
source share

All Articles