3v4l.org

run code in 500+ PHP versions simultaneously
<?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.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
string(34) "this! string contains, many. words"

preferences:
73.92 ms | 1399 KiB | 4 Q