Skip to content

Instantly share code, notes, and snippets.

@ryzr
Last active July 23, 2018 04:19
Show Gist options
  • Save ryzr/95ae038703ad6ec85cda6c474be7c6de to your computer and use it in GitHub Desktop.
Save ryzr/95ae038703ad6ec85cda6c474be7c6de to your computer and use it in GitHub Desktop.
Laravel Str Macros
<?php
Str::macro('sentences', function($value, $sentences = 2, $end = '...')
{
preg_match('/(.+?(?:(?<![\s.]\p{Lu})[.!?])){1,'.$sentences.'}/u', $value, $matches);
if (! isset($matches[0]) || static::length($value) === static::length($matches[0])) {
return $value;
}
return rtrim($matches[0]).$end;
});
Str::macro('paragraphs', function($value, $paragraphs = 3, $end = '...')
{
preg_match('/(.+?(?:\s{2,})|\n*){1,'.$paragraphs.'}/um', $value, $matches);
if (! isset($matches[0]) || static::length($value) === static::length($matches[0])) {
return $value;
}
return rtrim($matches[0]).$end;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment