Search

Use Str::slug before you write another regex

Use Str::slug before you write another regex

A surprising amount of “I need a regex” in Laravel is Str::slug, Str::snake, Str::kebab, Str::camel, Str::headline, or Str::mask. Title to URL, env key to label, email to a log-safe form: those are helpers with tests in the framework. A custom pattern is a comment you will not write.

Also Read: From an API JSON PHP payload to $fillable and $casts

The whitelist that is worth knowing

limit and words for excerpts. squish for pasted whitespace. ascii before a slug if you still care about transliteration. before / after / between for “the bit inside the brackets”. startsWith, endsWith, contains instead of str_contains with three extra flags. finish and start so paths always have exactly one slash on the side you meant.

Also Read: Laravel: Can you run

The Str helper playground only allows that whitelist, so you cannot call arbitrary PHP through the page. Use it to see what headline does to php_regex_tester, or what mask does to an email, then paste the call into the app.

Also Read: 220 billable days: turning a day rate into take-home pay

When the helper is the wrong tool

Capture groups, repeated tokens, “all hashtags in this caption”: that is still preg_match. JSON keys becoming class names often want studly after you have the array in PHP. Do not slug a datetime; format it.

If you are tempted to wrap Str::slug in a regex “just to strip punctuation first”, you are fighting the helper. Give it the raw title and look at the output.

Tags:
TWT Staff

TWT Staff

Writes about Programming, tech news, discuss programming topics for web developers (and Web designers), and talks about SEO tools and techniques

Your experience on this site will be improved by allowing cookies Cookie Policy