🐶
PHP

PHP String Contains: Check for Specific Words

By Filip on 10/16/2024

Learn several methods in PHP to efficiently check if a string contains a specific word, from built-in functions to regular expressions.

PHP String Contains: Check for Specific Words

Table of Contents

Introduction

In PHP, determining whether a string contains a specific word can be achieved through various methods. This article will guide you through two common approaches, highlighting their use cases and providing clear code examples.

Step-by-Step Guide

To check if a string contains a specific word in PHP, you can use the following methods:

1. Using str_contains() (PHP 8 and above):

$string = "This is a test string.";
$word = "test";

if (str_contains($string, $word)) {
    echo "The string contains the word '$word'.";
} else {
    echo "The string does not contain the word '$word'.";
}

2. Using strpos() (PHP 7 and earlier):

$string = "This is a test string.";
$word = "test";

if (strpos($string, $word) !== false) {
    echo "The string contains the word '$word'.";
} else {
    echo "The string does not contain the word '$word'.";
}

Explanation:

  • str_contains(): This function returns true if the string contains the specified word, and false otherwise.
  • strpos(): This function returns the position of the first occurrence of the word in the string. If the word is not found, it returns false. We use !== to compare the result with false because strpos() can return 0 if the word is found at the beginning of the string.

Note:

  • Both str_contains() and strpos() are case-sensitive.
  • If you need to perform a case-insensitive search, you can use stripos() instead of strpos().
  • If you need to check for the presence of a word as a whole word, you can use regular expressions with preg_match().

Code Example

The PHP code checks if a string contains a specific word using different methods: str_contains(), strpos(), stripos(), and preg_match(). It demonstrates both case-sensitive and case-insensitive searches, as well as searching for the whole word. The output confirms whether the word "test" is found in the string using each method.

<?php

// String to search in
$string = "This is a test string.";

// Word to search for
$word = "test";

// 1. Using str_contains() (PHP 8 and above)
if (str_contains($string, $word)) {
    echo "Using str_contains(): The string contains the word '$word'.\n";
} else {
    echo "Using str_contains(): The string does not contain the word '$word'.\n";
}

// 2. Using strpos() (PHP 7 and earlier)
if (strpos($string, $word) !== false) {
    echo "Using strpos(): The string contains the word '$word'.\n";
} else {
    echo "Using strpos(): The string does not contain the word '$word'.\n";
}

// Case-insensitive search using stripos()
if (stripos($string, "TEST") !== false) {
    echo "Using stripos(): The string contains the word 'TEST' (case-insensitive).\n";
} else {
    echo "Using stripos(): The string does not contain the word 'TEST' (case-insensitive).\n";
}

// Using preg_match() for whole word search
if (preg_match("/\b$word\b/", $string)) {
    echo "Using preg_match(): The string contains the whole word '$word'.\n";
} else {
    echo "Using preg_match(): The string does not contain the whole word '$word'.\n";
}

?>

This code demonstrates all the methods mentioned in the article:

  • str_contains(): Checks if the string contains the word "test".
  • strpos(): Checks if the string contains the word "test".
  • stripos(): Performs a case-insensitive search for the word "TEST".
  • preg_match(): Uses a regular expression to check for the presence of the word "test" as a whole word.

This code will output:

Using str_contains(): The string contains the word 'test'.
Using strpos(): The string contains the word 'test'.
Using stripos(): The string contains the word 'TEST' (case-insensitive).
Using preg_match(): The string contains the whole word 'test'.

Additional Notes

  • Performance: For simple checks, strpos() might be slightly faster than str_contains(), especially in older PHP versions. However, the difference is usually negligible.
  • Alternatives: Other functions like strstr() and stristr() can also be used to check for substrings, but they return the matched substring instead of a boolean or position.
  • Word Boundaries: Using preg_match() with word boundaries (\b) is crucial when you want to match a specific word and not just a sequence of characters. For example, you might want to match "test" but not "testing".
  • Character Encoding: Ensure that the string and the word you are searching for have the same character encoding (e.g., UTF-8) to avoid unexpected results.
  • Security: If you are working with user-supplied data, be cautious about using the word directly in a regular expression without proper escaping. Consider using preg_quote() to escape any special characters in the word.
  • Readability: While strpos() might be slightly faster in some cases, str_contains() often leads to more readable and self-explanatory code, especially for developers unfamiliar with the nuances of strpos() returning 0 for a match at the beginning of the string.
  • Context: The choice of method depends on the specific requirements of your application. If you need the position of the word, use strpos(). If you need a case-insensitive search, use stripos(). If you need to match a whole word, use preg_match(). Otherwise, str_contains() is a good default choice for PHP 8 and above.

Summary

Method PHP Version Description Case-Sensitive
str_contains($string, $word) 8+ Returns true if $string contains $word, otherwise false. Yes
strpos($string, $word) 7 and earlier Returns the position of $word in $string. Returns false if not found. Use !== false for comparison. Yes

Notes:

  • For case-insensitive searches, use stripos() instead of strpos().
  • To check for whole words, use regular expressions with preg_match().

Conclusion

In conclusion, PHP offers multiple ways to check if a string contains a specific word. For PHP 8 and above, str_contains() provides a straightforward solution. For earlier versions, strpos() is a reliable option, remembering to compare its return value with !== false. For case-insensitive searches, stripos() is the appropriate choice. When searching for a whole word, regular expressions with preg_match() and word boundaries (\b) are recommended. The best method depends on the specific needs of your application, considering factors like PHP version, case sensitivity, and whole-word matching. Always prioritize code readability and security, especially when handling user-provided data.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait