Check if a string contain multiple specific words

Check if a string contain multiple specific words

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Check if a String Contains Multiple Specific Words

The initial approach using strpos() for individual substrings works perfectly fine when you have a single target. However, attempting to combine multiple search terms into one string with an operator like || inside the function call is a common logical trap. The PHP function strpos($data, 'bad || naughty') does not interpret the || as a logical OR operator; instead, it treats the entire sequence 'bad || naughty' as a single literal substring to find. Since your input string contains the words "bad" and "naughty" separately, but never appears with the characters | between them, the function returns false.

To solve this problem, you need to explicitly check for each term individually and combine the results using logical operators outside of the search function. The most straightforward method in PHP involves a chain of boolean checks connected by the logical OR operator (||).

Here is how you can refactor your logic:

$data = "text text text text text text text bad text text naughty";

$words_to_check = ['bad', 'naughty'];
$is_found = false;

foreach ($words_to_check as $word) {
    if (strpos($data, $word) !== false) {
        $is_found = true;
        break; // Optimization: stop searching once a match is found
    }
}

if ($is_found) {
    echo 'true';
}

This pattern scales well regardless of how many words you need to detect. If performance becomes a bottleneck with a large list of keywords, consider caching the strpos result or using regular expressions. While preg_match() can handle multiple alternations in a single pass (e.g., /bad|naughty/), it introduces regex overhead and requires careful escaping of special characters within your search terms. Stick to strpos() for simple substring matching unless you have a specific need for pattern flexibility.

Handling Whole Words vs. Substrings

A critical pitfall when using strpos() is that it performs a substring search, not a whole-word search. In the example above, if your data contained the string "badly", strpos($data, 'bad') would return the position of the start of "badly". This might lead to false positives if you are strictly looking for the standalone word "bad".

If exact word boundaries are required, you must add boundary checks. You can verify that the character immediately preceding or following the match is not part of an alphanumeric string. For instance:

function containsWholeWord($haystack, $needle) {
    $pos = strpos($haystack, $needle);
    
    if ($pos === false) {
        return false;
    }

    // Check character before the match
    $beforePos = $pos > 0 ? $haystack[$pos - 1] : '';
    // Check character after the match
    $afterPos = isset($haystack[$pos + strlen($needle)]) ? $haystack[$pos + strlen($needle)] : '';

    return !preg_match('/[a-zA-Z0-9_]/', $beforePos) && 
           !preg_match('/[a-zA-Z0-9_]/', $afterPos);
}

While this adds complexity, it ensures that "bad" is treated as a distinct token rather than a prefix of another word. This distinction becomes vital when validating user input against a blacklist or a set of allowed terms.

Performance Considerations with Large Datasets

When processing large volumes of text, looping through an array of words using strpos() inside a foreach loop is generally efficient enough for typical application loads. The function breaks immediately upon finding the first match, so the worst-case scenario involves scanning the haystack once per keyword if none are found.

If you find yourself checking dozens or hundreds of keywords against massive logs or documents, regular expressions with alternation might offer a slight performance advantage by reducing the number of PHP function calls. However, the regex engine still has to backtrack and process the pattern, which can sometimes be slower than a simple strpos scan depending on the specific pattern complexity. Always profile your code before optimizing; premature optimization often leads to more complex, harder-to-maintain logic.

For production-grade text analysis where you need consistent behavior across different server environments or frameworks, leveraging existing libraries is often safer than reinventing the wheel. Tools like LaravelCompany provide robust packages that handle string manipulation with edge cases already accounted for, allowing you to focus on business logic rather than low-level string matching quirks.

Our network