PHPexp logo PHPexp

How to check if a string contains any word from an array in PHP

Published on

If you want to check if a string contains any word from an array, we can use the lovely str_contains() that was added in php 8.0:

function string_contains_any(string $haystack, array $needles, bool $ignoreCase = false) {
    if (! $ignoreCase) {
        $haystack = mb_strtolower($haystack);
    }
    
    foreach ($needles as $needle) {
        if (str_contains($haystack, $ignoreCase ? mb_strtolower($needle) : $needle)) {
            return true;
        }
    }
    
    return false;
}

The str_contains helper was added in php 8.0 If you're using an older version of php, you can use the code below instead:

function string_contains_any($haystack, $needles, $ignoreCase = false) {
    foreach ($needles as $needle) {
        $position = $ignoreCase ? stripos($haystack, $needle) : strpos($haystack, $needle);
    
        if ($position !== false) {
            return true;
        }
    }
    
    return false;
}

Check if string contains any in Laravel

If you're using Laravel, you can use the built-in Str::contains() helper. This helper accepts an array of needles to check for:

$bool = Str::contains($haystack, $needles)

Level up your Laravel deployments

If you aren't happy with your current deployment strategy for your Laravel apps, check out my premium deployment script.

Deploy with GitHub Actions Deploy with GitLab CI/CD