'Cut the string to particular length and preserve whole words
What would be the best way to, given a string $s and character limit $l, cut the $s so that whole words are preserved.
Example:
$s = 'Hello World.';
$l = 7;
function shorten( $a, $b ) { ... }
// Function should return 'Hello'
I've tried doing it with wordwrap( $s, $l, ';;;' ); and then substr( $s, strpos( ';;;', $l ) ); but that seems awful.
Solution 1:[1]
preg_replace will help you here:
$strings = [
'Word',
'Length.',
'Hello World.',
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
];
$length = 7;
foreach( $strings as $string ){
print
$string
. ' => '
. preg_replace("/(.{{$length}}[^\s]*).*/s", "$1", $string)
. "\n";
}
Output:
Word => Word
Length. => Length.
Hello World. => Hello World.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. => Lorem ipsum
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jared |
