# PHP Check If a String Contains a Specific Word or Substring

> Use str_contains() in PHP 8+ or strpos() in earlier versions to check whether a string contains a specific word, with examples of strict comparison

**URL:** https://sentry.io/answers/how-do-i-check-if-a-string-contains-a-specific-word-in-php/

---

## 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:

```php
$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:

```php
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:

```php
$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:

```php
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:

```php
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'
```

---

*Source: [sentry.io/answers/how-do-i-check-if-a-string-contains-a-specific-word-in-php/](https://sentry.io/answers/how-do-i-check-if-a-string-contains-a-specific-word-in-php/)*
