Skip to content

Instantly share code, notes, and snippets.

@gRegorLove
Last active March 12, 2024 18:23
Show Gist options
  • Save gRegorLove/0104ccdaec07b300ab3b591f3283b900 to your computer and use it in GitHub Desktop.
Save gRegorLove/0104ccdaec07b300ab3b591f3283b900 to your computer and use it in GitHub Desktop.
<?php
/**
* Get a specified number of characters from the start of a string.
* Avoids breaking mid-word.
*/
function get_characters(string $string, int $length = 10)
{
if (mb_strlen($string) <= $length) {
return $string;
}
$regex = '/^.{1,' . $length . '}\b/s';
preg_match($regex, $string, $match);
return trim($match[0]) . '…';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment