- substr: documentation ( source)
- var_dump: documentation ( source)
- str_word_count: documentation ( source)
<?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));