简体   繁体   English

使用正则表达式来检查字符串是否以一个下划线和两个字母以php结尾

[英]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. 我正在尝试检查在旧的php系统中字符串是否以_和两个字母结尾。 I've check here on stackoverflow for answers and I found one that wanted to do the same but with one . 我在这里检查了stackoverflow的答案,我发现有一个想做同样的事情,但有一个. 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: 然后我去了php并尝试了这个:

$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). 您会收到此错误,因为在PHP中,每个正则表达式都需要一个定界符(不使用/ ,它可以是~等其他任何字符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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