I know how to find substrings using strpos, but I want to return True only if the letter t appears in a string, but not if that t is followed by "he". For example...
$str="The lion and dog are hungry"
Does not contain t
$str="Their bedroom is ugly"
$str="The cat and the dog are hungry"
Yes, this string contains a t
You need a negative lookbehind regex:
See the regex demo
t- a literal char
(?!h(?:e|is))- a negative lookbehind that checks if its pattern matches the string after the current location and failing the match (returning false) if the match occurs:
h- a literal
(?:...|...)is a non-capturing group that does not keep submatches in the memory containing a
/i- case insensitive modifier making the regex match in a case insensitive way.
Basically, this is a more efficient version of a
t(?!he|his) regex (
t not followed with
$re = '/t(?!h(?:e|is))/i'; if (preg_match($re,'The cat and the dog are hungry')) echo 'true'; else echo 'false';