What is the difference between using ! and ^ in regular expressions in PHP?
In regular expressions in PHP, the exclamation mark (!) is used as a negative lookahead assertion, which matches any string that is not followed by a specific pattern. On the other hand, the caret (^) is used to match the start of a string. So, the main difference is that ! is used to exclude a specific pattern, while ^ is used to match the beginning of a string.
// Using ! to exclude a specific pattern
$pattern = '/hello(?!world)/';
$string = 'hello there';
if (preg_match($pattern, $string)) {
echo 'Match found!';
} else {
echo 'No match found.';
}
// Using ^ to match the start of a string
$pattern = '/^hello/';
$string = 'hello there';
if (preg_match($pattern, $string)) {
echo 'Match found!';
} else {
echo 'No match found.';