How to check if a string contains a specific word in PHP

Created
Modified

Using strpos Function

The strpos(string $haystack, string $needle, int $offset = 0): int|false function finds the numeric position of the first occurrence of needle in the haystack string. For example,

$str = "hello";
$pos = strpos($str, "l");
var_dump($pos);

$pos = strpos($str, "b");
var_dump($pos);
int(2)
bool(false)

Using preg_match Function

A simple match for are could look something like this:

$str = "hello";
$m = preg_match("/lo/i", $str);
var_dump($m);

$m = preg_match("/b/i", $str);
var_dump($m);
int(1)
int(0)

Related Tags

#string#