Eilutės skaldymas į žodžių masyvą pagal norimą simbolių ilgį (PHP)

Prireikė tokios funkcijos, kuri eilutę padalintų į žodžių masyvą pagal norimą simbolių skaičių, tačiau “nenukastų” žodžių. Tarkim jeigu 3 žodžiai viršija simbolių ribą, tokių atveju paimti tik tai du. taigi, šiuo atveju PHP funkcija chunk_split netinka.

Kodas:

  1. function stringToWords($string, $chars) {
  2.  
  3.  $words = explode(' ', $string);
  4.  $n = count($words);
  5.  $first = 0;
  6.  
  7.  while($first <= $n) {
  8.  
  9.   $new_str .= ' '.$words[$first];
  10.   $new_len = strlen($new_str);
  11.  
  12.   if($new_len > $chars) {
  13.    $new[] = substr($tmp_str, 1);
  14.    $new_str = '';
  15.   } else {
  16.    if($first == $n) {
  17.     $new[] = substr($new_str,1);
  18.    }
  19.    $first++;
  20.    $tmp_str = $new_str;
  21.   }
  22.  }
  23.  return $new;
  24. }

Pavyzdys:

  1. <?php
  2. $s = 'It is a long established fact that a reader will be distracted by the
  3.        readable content of a page when looking at its layout. ';
  4. print_r(stringToWords($s, 25));
  5. ?>
  6. Rezultatas:
  7. Array
  8. (
  9.     [0] => It is a long established
  10.     [1] => fact that a reader will
  11.     [2] => be distracted by the
  12.     [3] => readable content of a
  13.     [4] => page when looking at its
  14.     [5] => layout.  
  15. )
Data 2009.11.20

Leave a Reply

You must be logged in to post a comment.