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));

preferences:
27.33 ms | 409 KiB | 5 Q