Sentry Answers>PHP>

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

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:

Click to Copy
$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:

Click to Copy
1

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

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

Output:

Click to Copy
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:

Click to Copy
$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:

Click to Copy
// 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:

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

Output:

Click to Copy
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:

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

Will return:

Click to Copy
The string 'http://' is NOT in 'http://www.example.com/info/about-us'
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,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.

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