contains() and startsWith()

Search inside strings with contains(), startsWith() and endsWith().

Syntax\Illuminate\Support\Str::contains($haystack, $needle);

These boolean helpers answer common questions about a string:

  • Str::contains() — does it include a substring?
  • Str::startsWith() — does it begin with a value?
  • Str::endsWith() — does it end with a value?

Each can accept an array of needles to check several at once.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A request filter checks whether the User-Agent header contains 'bot' with Str::contains() to rate-limit crawler traffic differently from real users.
  • A content moderation pipeline uses Str::contains() with an array of banned words to flag submissions for human review.
  • A routing guard uses Str::startsWith() on the request path to detect admin routes and enforce additional two-factor authentication.

More examples

Check a substring is present

Str::contains() returns a boolean indicating whether the needle appears anywhere in the haystack.

Example · php
use Illuminate\Support\Str;

$email = '[email protected]';

Str::contains($email, '@example.com');  // true
Str::contains($email, 'gmail');         // false

Match any of multiple substrings

Passing an array as the second argument makes Str::contains() return true if any one of the values is found.

Example · php
use Illuminate\Support\Str;

$ua = 'Mozilla/5.0 (compatible; Googlebot/2.1)';

// Pass an array to match ANY value
$isBot = Str::contains($ua, ['Googlebot', 'Bingbot', 'Slurp']);
// => true

startsWith and endsWith guards

Uses startsWith() and endsWith() as guard conditions to apply different logic based on the prefix or suffix of a string.

Example · php
use Illuminate\Support\Str;

$path = '/admin/users/42';

if (Str::startsWith($path, '/admin')) {
    // enforce 2FA
}

$file = 'report_2025.pdf';
if (Str::endsWith($file, '.pdf')) {
    // serve inline instead of as download
}

Discussion

  • Be the first to comment on this lesson.