简体   繁体   中英

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)?

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

This should do it for you.

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

    preg_match($re, $str);

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM