Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Adds Str::excerpt #41000

Merged
merged 9 commits into from
Feb 14, 2022
Merged

[9.x] Adds Str::excerpt #41000

merged 9 commits into from
Feb 14, 2022

Conversation

nunomaduro
Copy link
Member

This pull request adds the Str::excerpt method to Laravel 9.

The original idea comes from Rails ActionView::Helpers::TextHelper::excerpt, and extracts an excerpt from the given $text that matches the first instance of $phrase.

public static function excerpt($text, $phrase = '', $options = [])

In other words, it just creates a relevant excerpt that contains the given $phrase:

// Description: Laravel is a web application framework with expressive, elegant syntax.
// Search: Framework
$article = Article::search($request->search)->get()->first();

// Excerpt: ...plication framework with expr...
$excerpt = str($article->description)->excerpt($request->search, [
    'radius' => 10,
]);

The radius option expands the excerpt on each side of the first occurrence of $phrase by the number of characters defined in radius (which defaults to 100). If the excerpt radius overflows the beginning or end of the $text, then the $omission option (which defaults to "...") will be prepended/appended accordingly:

// Excerpt: ...on framework wi...
// The left side with radius is: "on ".
// The right side with radius is: " wi".
$excerpt = str($article->description)->excerpt($request->search, [
    'radius' => 3,
]);

// Excerpt: ???on framework wi???
$excerpt = str($article->description)->excerpt($request->search, [
    'radius' => 3,
    'omission' => '?'
]);

Of course, if the excerpt radius does not overflows the beginning or end of the $text, the no omission is applied:

// Excerpt: '......el  Framework'
$excerpt = str('Laravel Framework')->excerpt('Framework', [
    'radius' => 3,
    'omission' => '......'
]);

If the $phrase isn't found, null is returned:

// Excerpt: null
$excerpt = str($article->description)->excerpt('This does not exist on text');

@martindilling
Copy link

martindilling commented Feb 14, 2022

So highlight next? ;)
https://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-highlight

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants