rafaelmorais
rafaelmorais

Reputation: 1383

Regular Expression to check if string ends with one underscore and two letters with php

I'm trying to check if a string ends with one _ and two letters on an old system with php. I've check here on stackoverflow for answers and I found one that wanted to do the same but with one . and two digits.

I tried to change it to work with my needs, and I got this:

\\.*\\_\\a{2,2}$

Then I went to php and tried this:

$regex = '(\\.*\\_\\a{2,2}$)'; echo preg_match($regex, $key);

But this always returns an error, saying the following:

preg_match(): Delimiter must not be alphanumeric or backslash

I get this happens because I can't use the backslashes or something, how can I do this correctly? And also, is my regex correct(I don't know ho to form this expressions and how they work)?

Upvotes: 1

Views: 918

Answers (2)

vks
vks

Reputation: 67968

^.*_[a-zA-Z]{2}$

This should do it for you.

    $re = "/^.*_[a-zA-Z]{2}$/"; 
    $str = "abc_ac"; 

    preg_match($re, $str);

Upvotes: 1

anubhava
anubhava

Reputation: 785156

You can use this regex with delimiters:

$regex = '/_[a-z]{2}$/i';

You're getting that error because in PHP every regex needs a delimiter (not use of / above which can be any other character like ~ also).

Upvotes: 1

Related Questions