Coding Triumph

Helpful code snippets & tutorials

How to check if a specific word exists in a string with PHP

Depending on the PHP version, there are two functions you can use to find a specific word in a string:

Before PHP 8:

You can use the strpos() function:

strpos(
    string $haystack, # the string to search in
    string $needle,   # the substring to search for
    int $offset = 0   # the position the search starts from
): int|false          # returns the position of the needle in the haystack or false if not found

And this is a useful example:

// returns true if $needle is a substring of $haystack or false if not
function contains($needle, $haystack)
{
    return strpos($haystack, $needle) !== false;
}

$haystack = 'How are you';
$needle = 'are';

$is_needle_in_haystack = contains($needle, $haystack);

var_dump($is_needle_in_haystack); # prints "bool(true)"

With PHP 8+:

PHP 8 comes with a new built-in function to determine if a string contains a given substring; the str_contains() function:

str_contains(
    string $haystack, # the string to search in
    string $needle    # the substring to search for in the haystack
): bool               # returns true if needle is in haystack, false otherwise

And a simple example:

$haystack = 'How are you';
$needle = 'are';

$is_needle_in_haystack = str_contains($haystack, $needle);

var_dump($is_needle_in_haystack); # prints "bool(true)"
If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments