我想出了一种没有RegEx的方法,但是你的条件仍然匹配:
function my_func($str) {
$letters = 'abcdefghijklmnopqrstuvwxyz';
$match = true; // Will be set to false if does not match conditions
$l1pos = strrpos($letters, $str[0]);
$l2pos = strrpos($letters, $str[1]);
$l3pos = strrpos($letters, $str[2]);
$l4pos = strrpos($letters, $str[3]);
$l5pos = strrpos($letters, $str[4]);
// If letter 2 comes before letter 1
if ($l2pos < $l1pos) { $match = false;}
// If letter 3 comes before letter 2
if ($l3pos < $l2pos) { $match = false; }
// If letter 4 comes after letter 3
if ($l4pos >= $l3pos) { $match = false; }
// If letter 5 comes after letter 4
if ($l5pos >= $l4pos) { $match = false; }
return $match;
}
您可以像这样使用它:
$string = 'apple';
if (my_func($string)) {
print 'Matched!';
}
else {
print 'Not Matched. :(';
}
如果你想让函数真的很小,你可以使用以下代码:
function my_func($str) {
$letters = 'abcdefghijklmnopqrstuvwxyz';
$match = true;
function m($i) {
return strrpos($letters, $str[$1]);
}
if ((m(1) < m(0)) || (m(2) < m(1)) || (m(3) >= m(2)) || (m(4) >= m(3))) {
$match = false;
}
return $match;
}
我也尝试过RegEx,并得到以下信息:
^([a-z]) # First Letter
([\1-z]) # Second Letter
([\2-z]) # Third Letter
([a-\3]) # Fourth Letter
([a-\4]) # Fifth Letter
但是,在将a或z动态设置为先前捕获的组之一时,不能使用a-z.你可以使用PHP连接来创建一个RegEx,但这需要至少4行代码,每个字母只有第一行.