Last active
February 5, 2024 17:35
-
-
Save ronssij/d405cd6a06148a409daec90721831062 to your computer and use it in GitHub Desktop.
Jsutify string in PHP(Laravel)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed turpis adipiscing sodales ipsum sem ac. Orci sem nisl rutrum sagittis sed id. In tellus mauris tempor in at. Lorem ac sit tortor, eu sit elementum vestibulum ultrices egestas. In nunc, aliquet nulla quis. Tristique molestie integer ac ullamcorper dolor. Donec id erat turpis lobortis et egestas phasellus. Sit elit suspendisse porttitor egestas. Augue id mollis enim, eget sapien, luctus. Tortor, malesuada morbi et dui pretium adipiscing dui id rhoncus. Vitae et eget luctus ut nec donec. Vulputate pharetra tempus, congue eu commodo praesent imperdiet sapien. Vitae eleifend lobortis tellus enim, aliquam fermentum at venenatis. Mattis fringilla id viverra in metus pharetra, rutrum eget porta."; | |
$limit = 30; | |
$lines = []; | |
$collected = collect([]); | |
$words = explode(" ", $string); | |
collect($words)->each(function ($word) use ($limit, &$lines, $collected) { | |
$try = array_merge($lines, [$word]); | |
if (strlen(implode(" ", $try)) <= $limit) { | |
return array_push($lines, $word); | |
} | |
$collected->push(collect($lines)); | |
$lines = [$word]; | |
}); | |
return $collected->map(function ($line) use ($limit) { | |
$spacesToAdd = $limit - strlen( $string = $line->join(" ")); | |
if ($spacesToAdd > 0) { | |
$wordCount = count($line) - 1; | |
while ($spacesToAdd > 0) { | |
for ($i = 0; $i < $wordCount && $spacesToAdd > 0; $i++) { | |
$line[$i] .= ' '; | |
$spacesToAdd--; | |
} | |
} | |
return implode(' ', $line->toArray()); | |
} | |
})->filter()->implode(PHP_EOL); | |
``` | |
""" | |
Lorem ipsum dolor sit amet,\n | |
consectetur adipiscing elit.\n | |
Sed turpis adipiscing sodales\n | |
ipsum sem ac. Orci sem nisl\n | |
rutrum sagittis sed id. In\n | |
tellus mauris tempor in at.\n | |
Lorem ac sit tortor, eu sit\n | |
elementum vestibulum ultrices\n | |
egestas. In nunc, aliquet\n | |
integer ac ullamcorper dolor.\n | |
Donec id erat turpis lobortis\n | |
Augue id mollis enim, eget\n | |
sapien, luctus. Tortor,\n | |
adipiscing dui id rhoncus.\n | |
Vitae et eget luctus ut nec\n | |
donec. Vulputate pharetra\n | |
tempus, congue eu commodo\n | |
praesent imperdiet sapien.\n | |
enim, aliquam fermentum at\n | |
viverra in metus pharetra, | |
""" | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment