What are the differences between preg_match and preg_grep in PHP regex?
The main difference between preg_match and preg_grep in PHP regex is that preg_match is used to search for a pattern in a string and returns true if a match is found, while preg_grep is used to search for a pattern in an array and returns an array containing the elements that match the pattern. If you need to search for a pattern in a single string, use preg_match. If you need to search for a pattern in an array of strings, use preg_grep.
// Using preg_match to search for a pattern in a string
$string = "Hello, World!";
$pattern = "/Hello/";
if (preg_match($pattern, $string)) {
echo "Pattern found in the string.";
} else {
echo "Pattern not found in the string.";
}
// Using preg_grep to search for a pattern in an array
$array = ["apple", "banana", "cherry"];
$pattern = "/an/";
$matches = preg_grep($pattern, $array);
print_r($matches);