CheeseFlavored CheeseFlavored - 1 year ago 62
PHP Question

php find a substring only if it's not part of another substring

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"

The result would be
Does not contain t
because the only t in the string was part of the word "The".
$str="Their bedroom is ugly"
should also return false because "Their" starts with T H E and there's not other t in the string.
$str="The cat and the dog are hungry"
would result in
Yes, this string contains a t
because there's a t in CAT.

Answer Source

You need a negative lookbehind regex:


See the regex demo

Pattern details:

  • t - a literal char t
  • (?!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 h
    • (?:e|is) - either e or is (the (?:...|...) is a non-capturing group that does not keep submatches in the memory containing a | alternation operator)
  • /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 he or his).

PHP demo:

$re = '/t(?!h(?:e|is))/i';

if (preg_match($re,'The cat and the dog are hungry'))
    echo 'true';
    echo 'false';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download