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:
-
function stringToWords($string, $chars) {
-
-
$words = explode(' ', $string);
-
$n = count($words);
-
$first = 0;
-
-
while($first <= $n) {
-
-
$new_str .= ' '.$words[$first];
-
$new_len = strlen($new_str);
-
-
if($new_len > $chars) {
-
$new[] = substr($tmp_str, 1);
-
$new_str = '';
-
} else {
-
if($first == $n) {
-
$new[] = substr($new_str,1);
-
}
-
$first++;
-
$tmp_str = $new_str;
-
}
-
}
-
return $new;
-
}
Pavyzdys:
-
<?php
-
$s = 'It is a long established fact that a reader will be distracted by the
-
readable content of a page when looking at its layout. ';
-
print_r(stringToWords($s, 25));
-
?>
-
Rezultatas:
-
Array
-
(
-
[0] => It is a long established
-
[1] => fact that a reader will
-
[2] => be distracted by the
-
[3] => readable content of a
-
[4] => page when looking at its
-
[5] => layout.
-
)
2009.11.20

