3v4l.org

run code in 300+ PHP versions simultaneously
<?php function a($string, $length) { $string = substr($string, 0, $length); $string = substr($string, 0, strrpos($string, ' ')); return $string; } function b($string, $length) { $words = explode(' ', $string); $string = array_reduce($words, function ($current, $item) use ($length) { return mb_strlen($current) > $length ? $current : "$current$item "; }, ''); return $string; } $length = 40; $string = 'The fox flew over the moon. The cow did a big twist into the pool.'; var_dump(a($string, $length)); var_dump(b($string, $length));
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.29, 8.2.0 - 8.2.20, 8.3.0 - 8.3.8
string(39) "The fox flew over the moon. The cow did" string(42) "The fox flew over the moon. The cow did a "

preferences:
96.56 ms | 402 KiB | 94 Q