Yaldram Yaldram - 2 months ago 37
PHP Question

PHP str word count divide equal parts

i have text file that have 100k word.php function str_word_count() works and echo me 100k in text file.but i want divide 100k words into 4 equal parts.

$data=file_get_contents('100k.txt');
echo $count=str_word_count($data);

Answer

Use str_split() to split your string into parts. The second argument in str_split is the number of pieces you want to split the string into. The following will count the length of your string, then give you an array containing the string as four array items in the array $pieces.

$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque facilisis ultricies efficitur. Integer mattis tincidunt risus id interdum. Integer nulla tellus, imperdiet vitae dui et, sagittis tempus lorem. Maecenas aliquet volutpat purus, sed finibus turpis imperdiet sed. Aliquam erat velit, viverra in nisi vel, euismod porta metus. Vivamus id mi tellus. Fusce sodales dolor dignissim lorem vehicula malesuada. Fusce a tortor in massa viverra blandit. Mauris sit amet sem ligula. Nullam et ullamcorper mi. In porta semper purus a auctor. Cras eget ipsum ut sapien condimentum venenatis vitae ut sem.";

$length = strlen($text);
$pieces = str_split($text, ceil($length/4));
Comments