Skip to content

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

Merged
taylorotwell merged 9 commits into
9.xfrom
feat/str-excerpt
Feb 14, 2022
Merged

[9.x] Adds Str::excerpt#41000
taylorotwell merged 9 commits into
9.xfrom
feat/str-excerpt

Conversation

@nunomaduro

Copy link
Copy Markdown
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

martindilling commented Feb 14, 2022

Copy link
Copy Markdown

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

Comment thread src/Illuminate/Support/Str.php Outdated
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