<?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));
- Output for 7.1.25 - 7.1.27, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
- string(34) "this! string contains, many. words"
preferences:
144.12 ms | 407 KiB | 5 Q