<?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.31, 8.2.0 - 8.2.26, 8.3.0 - 8.3.14, 8.4.1
- string(39) "The fox flew over the moon. The cow did"
string(42) "The fox flew over the moon. The cow did a "
preferences:
66.06 ms | 406 KiB | 5 Q