How do I check if a string contains a specific word in PHP?

Nadia S.

The Problem

How do I check if a string contains a specific word in PHP?

The Solution

Since PHP 8, we can use the str_contains() function to check if a substring is present within a given string. In this example, we check whether a string URL has the http:// protocol:

$url = "http://www.example.com/info/about-us"; $protocol = 'http://'; // check $url for the presence of the $protocol substring echo str_contains($url, $protocol);

The function returns 1 for true:

1

You can use an if statement to echo out a string literal of the result, for example:

if (str_contains($url, $protocol)) { echo 'true'; } else { echo 'false'; }

Output:

true

The strpos() function

Versions of PHP previous to PHP 8 use the less intuitive strpos() function to determine if a string contains a certain substring.

The strpos() function returns an integer of the substring’s starting position if the substring is present, for example:

$url = "http://www.example.com/info/about-us"; $protocol = 'http://'; $ans = strpos($url, $protocol); echo $ans;

The output tells us that $protocol is present and begins at the first character of $url:

// index value 0

In contrast to str_contains(), you need to explicitly include a comparator in an if statement, such as $foo === false. For example:

if ($ans === false) { echo "The string '$protocol' is NOT in '$url'"; } else { echo "The string '$protocol' is in '$url'"; }

Output:

The string 'http://' is in 'http://www.example.com/info/about-us'

Note that you must use the === comparator instead of == if there is any chance of the substring in question starting at index 0 or the value of 0 will be interpreted as equating to false. So this example:

if ($ans == false) { echo "The string '$protocol' is NOT in '$url'"; } else { echo "The string '$protocol' is in '$url'"; }

Will return:

The string 'http://' is NOT in 'http://www.example.com/info/about-us'

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.