21

这似乎很明显,但我找不到办法做到这一点。
我认为甚至有一个常规的 PHP 函数可以做到这一点,但即使是在 1.5 小时的密集谷歌搜索之后,它也能很好地隐藏起来。

我想要的是

  • 将字符串作为输入的函数。
  • 检查该字符串具有超过 3 个字符的按字母顺序排列的次数:
  • 如果找到超过 3 个的序列,则返回 true。

例子

"youlookgreatbcdetoday" => 里面有 "bcde" ... 所以必须返回 true
"youlookgreatklmtoday" => 里面只有 "klm" ... 所以必须返回 false
"youlookgreattoday" => 没有按字母顺序排列的序列在其中,所以返回 false


可能的用例

  • 密码强度检查器
  • 文字游戏
  • ...

免责声明:我希望我已经有一些代码可以向您展示,但实际上我还没有。
我唯一能想到的就是将字符串拆分成一个数组并在数组上做一些魔术......但即便如此我还是被卡住了。

希望你们中的一个人能救我:)

4

13 回答 13

17

因此,让我们从一个使用循环和计数器(仅用于递增)的简单实现开始:

function hasOrderedCharactersForward($string, $num = 4) {
    $len = strlen($string);
    $count = 0;
    $last = 0;
    for ($i = 0; $i < $len; $i++) {
        $current = ord($string[$i]);
        if ($current == $last + 1) {
            $count++;
            if ($count >= $num) {
                return true;
            }
        } else {
            $count = 1;
        }
        $last = $current;
    }
    return false;
}

那么它是怎样工作的?基本上,它循环并检查ord字符的(ascii 编号)是否比它之前的一个多一个。如果是这样,它会增加计数参数。否则,它将其设置为 1(因为我们已经处理了该字符)。然后,如果$count大于或等于请求的数字,我们知道我们找到了一个序列,并且可以返回......

所以,现在让我们检查两个方向:

function hasOrderedCharacters($string, $num = 4) {
    $len = strlen($string);
    $count = 0;
    $dir = 1;
    $last = 0;
    for ($i = 0; $i < $len; $i++) {
        $current = ord($string[$i]);
        if ($count == 1 && $current == $last - 1) {
            $count++;
            $dir = -1;
            if ($count >= $num) {
                return true;
            }
        } elseif ($current == $last + $dir) {
            $count++;
            if ($count >= $num) {
                return true;
            }
        } else {
            $count = 1;
            $dir = 1;
        }
        $last = $current;
    }
    return false;
}

现在,它会返回 true for abcdand dcba...

现在,这是一个更简单的解决方案:

function hasOrderedCharactersForward($string, $num = 4) {
    $len = strlen($string) + 1;
    $array = array_map(
        function($m) use (&$len) {
            return ord($m[0]) + $len--;
        }, 
        str_split($string, 1)
    );
    $str = implode('_', $array);
    $regex = '#(^|_)(\d+)' . str_repeat('_\2', $num - 1) . '(_|$)#';
    return (bool) preg_match($regex, $str);
}

你去吧。我们使用的属性是,如果我们向每个位置添加一个递减的数字,则连续序列将显示为相同的数字。这正是它的工作原理。

这是适用于两个方向的相同理论:

function hasOrderedCharacters($string, $num = 4) {
    $i = 0;
    $j = strlen($string);
    $str = implode('', array_map(function($m) use (&$i, &$j) {
        return chr((ord($m[0]) + $j--) % 256) . chr((ord($m[0]) + $i++) % 256);
    }, str_split($string, 1)));
    return preg_match('#(.)(.\1){' . ($num - 1) . '}#', $str);
}
于 2012-08-25T19:16:12.830 回答
4
<?php
function check($input, $length = 4)
{
    $sequence = "abcdefghijklmnopqrstuvwxyz";
    $sequence .= substr($sequence, 0, $length - 1);
    // abcdefghijklmnopqrstuvwxyz is converted to abcdefghijklmnopqrstuvwxyzabc
    for ($i = 0; $i < strlen($sequence) - $length; $i++) {
        // loop runs for $i = 0...25
        if (strpos($input, substr($sequence, $i, $length)) !== false) {
            echo sprintf('"%s" contains "%s"' . PHP_EOL, $input, substr($sequence, $i, $length));
            return true;
        }
    }
    echo sprintf('"%s" is OK' . PHP_EOL, $input);
    return false;
}
check("youlookgreatbcdetoday"); // "youlookgreatbcdetoday" contains "bcde"
check("youlookgreatklmtoday");  // "youlookgreatklmtoday" is OK
check("youlookgreattoday");     // "youlookgreattoday" is OK
check("youlookgreattodayza");   // "youlookgreattodayza" is OK
check("youlookgreattodayzab");  // "youlookgreattodayzab" contains "yzab"
于 2012-08-25T19:24:11.827 回答
4

更少的循环和 if 条件!

  function alphacheck($str, $i=4)
  {
      $alpha = 'abcdefghijklmnopqrstuvwxyz';
      $len = strlen($str);

      for($j=0; $j <= $len - $i; $j++){
          if(strrpos($alpha, substr($str, $j, $i)) !== false){
              return true;
          }
      }

      return false;
  }
于 2012-08-25T20:09:27.283 回答
2

这就是我想出的:

/**
 * @param string $input Input string
 * @param int $length Length of required sequence
 *
 * @return bool
 */

function look_for_sequence($input, $length) {
    //If length of sequence is larger than input string, no sequence is possible.
    if ($length > strlen($input)) {
        return false;
    }
    //Normalize string, only lowercase
    //(That's because character codes for lowercase and uppercase are different).
    $input = strtolower($input);

    //We loop until $length characters before the end of the string, because after that,
    //No match can be found.
    for ($i = 0; $i < strlen($input) - $length; $i++) {
        //Reset sequence counter
        $sequence = 1;
        //Character under inspection.
        $current_character = ord($input[$i]);
        //Let's look forward, $length characters forward:
        for ($j = $i + 1; $j <= $i + $length; $j++) {
            $next_character = ord($input[$j]);
            //If this next character is actually the sequencing character after the current
            if ($next_character == $current_character+1) {
                //Increase sequence counter
                $sequence++;
                //Reset the current character, and move to the next
                $current_character = $next_character;
                //If $length characters of sequence is found, return true.
                if ($sequence >= $length) {
                    return true;
                }
            }
            //If the next character is no sequencing,
            //break this inner loop and continue to the next character.
            else {
                break;
            }
        }
    }
    return false;
}

var_dump(look_for_sequence("youlookgreatbcdetoday", 4));

处理我扔给它的任何字符串,您还可以选择要计算的字符数!耶!

于 2012-08-25T19:38:29.380 回答
1

这是我的看法:

function checkConsecutiveness($string, $length = 3)
{

    $tempCount = 1; 

    for($i = 0; $i < count($tokens = str_split(strtolower($string)) ); $i++)
    {

        // if current char is not alphabetic or different from the next one, reset counter
        if(
            ord($tokens[$i]) < 97 ||
            ord($tokens[$i]) > 122 ||
            ord($tokens[$i]) != (ord( $tokens[$i+1]) -1)
        ){

            $tempCount = 1;

        }
        // else if we met given length, return true
        else if(++$tempCount >= $length)

            return true;

    }

    // no condition met by default
    return false;

}

它检查$string任何$length连续字母序列。

checkConsecutiveness('1@abcde1', 5) // returns true;
checkConsecutiveness('1@abcd1', 5) // returns false;

请注意确保当前字符在 97-122 范围内,因为勾号 `[ ASCII #96] 和大括号 { [ASCII #123] 可能会导致误报。

于 2012-08-25T19:51:29.433 回答
1

使用正则表达式也很简单:

preg_match('/  ((?=ab|bc|cd|de|ef|fg|gh).)  {2,}  /smix', "testabc")

您显然需要完成连续字母的列表。并且{2,}只需在一个范围内探测至少三个字母。

于 2012-08-25T19:32:49.003 回答
1

您可以尝试使用 PHPord()获取每个字符的 ASCII 值,并逐个字符地遍历字符串,比较每个值以查找序列。

这可能会有所帮助:

function checkForSequences($str, $minSequenceLength = 4) {
    $length = strlen($str);
    $sequenceLength = 1;
    $reverseSequenceLength = 1;
    for ($i = 1; $i < $length; $i++) {
        $currChar = ord(strtolower($str[$i]));
        $prevChar = ord(strtolower($str[$i - 1])) + 1;
        if ($currChar == $prevChar) {
            // we have two-letters back to back; increment the counter!
            $sequenceLength++;
            if ($sequenceLength == $minSequenceLength) {
                // we've reached our threshold!
                return true;
            }
            // reset the reverse-counter
            $reverseSequenceLength = 1;
        } else if ($currChar == ($prevChar - 2)) {
            // we have two-letters back to back, in reverse order; increment the counter!
            $reverseSequenceLength++;
            if ($reverseSequenceLength == $minSequenceLength) {
                // we've reached our threshold!
                return true;
            }
            // reset the forward-counter
            $sequenceLength = 1;
        } else {
            // no sequence; reset counter
            $sequenceLength = 1;
            $reverseSequenceLength = 1;
        }
    }
    return false;
}

这个函数将做的是,它将逐个字符地遍历字符串。它将ord()用于获取当前字符的 ASCII 值并将其与前一个字符的 ASCII 值进行比较。如果它们是按顺序排列的,无论是正向还是反向,它都会增加一个计数器。当计数器击中时4,它返回true!。

这将匹配正向和反向序列,以及忽略大小写。所以,abcd将匹配,aBcD将,还有DcBa,等等!

于 2012-08-25T19:15:07.410 回答
1

这是我想出的一个简单的解决方案:

function alphaCheck($str){
    $array=str_split(strtolower($str));
    $minMatchLength=3;
    $check=array(ord($array[0]));
    foreach($array as $letter){
        $ascii=ord($letter);
        if($ascii==end($check)+1){
            $check[]=$ascii;
            if(count($check)==$minMatchLength)
                return true;
        }else{
            unset($check);
            $check=array($ascii);
        }
    }
    return false;
}
$str="abcdhello";
$str2="testing";
$str3="abdcefghi";
if(alphaCheck($str))
    echo"STR GOOD";
if(alphaCheck($str2))
    echo "STR2 GOOD";
if(alphaCheck($str3))
    echo "STR3 GOOD";

输出为 STR GOOD 和 STR3 GOOD。 $minMatchLength是为了使函数返回 true,一行中的字符数。(“testing”有“st”,但长度是3,所以它返回false。

编辑 我更新了它以检查“AbCdE”,因为ord单独无法解决这个问题。

于 2012-08-25T19:16:11.680 回答
1

字符的不等式比较确实隐式使用 ord() 值。这是一个简单的脚本,可以对其进行调整(特别是不区分大小写):

<?php
$string = "thisabcdef";

function hasSequence($string, $sequence_length = 3) {
        $num_in_order = 0;
        for($i = 1; $i < strlen($string); $i++) {
                if($string[$i] > $string[$i-1]) {
                        $num_in_order++;
                } else {
                        $num_in_order = 0;
                }
                if($num_in_order >= $sequence_length) {
                        return TRUE;
                }
        }
        return FALSE;
}
if(hasSequence("testabcd")) {
        echo "YUP";
} else {
        echo "NOPE";
}
echo "\n";
于 2012-08-25T19:24:03.793 回答
1

可能很简单?如果您想要不区分大小写,则可以stripos()改用。

function abc($test, $depth) {
    $alpha = 'abcdefghijklmnopqrstuvwxyz';
    $matches = 0;
    $length = strlen($test);

    while ($length--) {
        $char = substr($test, $length, $depth);

        if (strlen($char) == $depth && strpos($alpha, $char) !== false) {
            $matches++;
        }

        if ($matches == $depth) return true;
    }

    return false;
}

http://codepad.org/tIySKnm4

并且(窃取 IRCMaxwell 的观察结果)strrev()

function abc($test, $depth) {
    $alpha = 'abcdefghijklmnopqrstuvwxyz';
    $matches = 0;
    $length = strlen($test);

    while ($length--) {
        $char = substr($test, $length, $depth);

        if (strlen($char) == $depth && 
            (strpos($alpha, $char) !== false || 
             strpos(strrev($alpha), $char) !== false)) {
            $matches++;
        }

        if ($matches == $depth) return true;
    }

    return false;
}

http://codepad.org/sjzrVAAg

于 2012-08-25T19:27:14.013 回答
0

我的两分钱:

function countOrderedCharacters($str, $count){
    $matches = array();
    preg_replace_callback('/(?=(\w{'.$count.'}))/',function($x) use(&$matches,$count) {
        $seq = $x[1];
        if($count === 1){
            $matches[] = $seq;
            return;
        }
        $dif = ord($seq[1]) - ord($seq[0]);
        if (abs($dif)!=1) return;
        for($i = 0 ; $i < strlen($seq)-1 ; $i++){
            if(ord($seq[$i+1]) - ord($seq[$i]) != $dif) return;
        }
        $matches[] = $seq;

    }, $str);
    return $matches;
}
于 2012-08-26T06:20:35.590 回答
0

你可以这样做(ASCII码按字母顺序排列):

function check_str_for_sequences($str, $min = 3) {
        $last_char_code = -1;
        $total_correct = 0;
        $str = strtolower($str);

        for($i = 0; $i < strlen($str); $i++) {
            //next letter in the alphabet from last char?
            if(ord($str[$i]) == ($last_char_code + 1)) {
                $total_correct++;

                //min sequence reached?
                if($total_correct >= ($min - 1)) {
                    return TRUE;
                }
            } else {
                $total_correct = 0;
            }

            $last_char_code = ord($str[$i]);
        }

        return FALSE;
    }

用法:

$test = 'Lorem ipsum dolor abcsit amet';

echo '----->' . check_str_for_alpha($test); // ----->1
于 2012-08-25T19:28:35.840 回答
-1

试试这个功能:

function checkForString($string,$l=4){
   $length = strlen($string);
   $result = 0;
   for($i=0;$i<$length-1 && $result<4;$i++){

   if($string[$i+1] == $string[$i]++) $result++;

}
if($result>=4) return true;
else return false;
}
于 2012-08-25T19:15:41.760 回答