phpregexvalidationnegative-lookbehindmention

Prevent matching @mentions if preceded by specific letters


I need to match all mentions without RT before. I've tried adding ! to negate the rt but don't work.

preg_match('/\b!rt\s*@([a-zA-Z0-9_]{1,20})/i', $string, $data);

this must match: hello @user how are you this not: RT @user how are you

I'm not trying to extract usernames or something, what I need is to know if the text has @user without RT.


Solution

  • ! doesn't "negate" in regex. That matches a literal !. What you want is a "Negative Lookbehind".

    /(?<!RT)\s@([a-z0-9]{1,20})/i
    

    (?<!RT) means "not preceded by "RT".

    This will match the username, the "RT" isn't included as a match.

    $match = preg_match('/(?<!RT)\s@([a-z0-9]{1,20})/i', $string);
    

    If $match is 0, it means the string was "RT @user ...". If $match is not 0, that means the string did not start with "RT @user".

    DEMO: http://ideone.com/bOWbu

    More info on regex lookarounds: http://www.regular-expressions.info/lookaround.html