<?php $str = 'this! string contains, many. words but I want 5'; function get5Words(string $str) { $words = str_word_count($str, 2); $cnt = 0; foreach($words as $strPos => $v) { if($cnt++ === 5) { return substr($str, 0, $strPos-1); } } return $str; } var_dump(get5Words($str));
You have javascript disabled. You will not be able to edit any code.