Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
$str = 'fD3_';
$chars = array_merge(range('a', 'z'), range('A', 'Z'), range('0', '9'), ['_']);
$total = 0;
$brut = '';
$len = strlen($str);
/**
* @see: https://www.programmingalgorithms.com/algorithm/brute-force?lang=PHP
*/
function BruteForce($testChars, $startLength, $endLength, $testCallback) {
for ($len = $startLength; $len <= $endLength; ++$len) {
for ($i = 0; $i < $len; ++$i) $chars[$i] = $testChars[0];
if ($testCallback($chars)) return implode("", $chars);
for ($i1 = $len - 1; $i1 > -1; --$i1) {
$i2 = 0;
$testCharsLen = strlen($testChars);
for ($i2 = strpos($testChars, $chars[$i1]) + 1; $i2 < $testCharsLen; ++$i2) {
$chars[$i1] = $testChars[$i2];
if ($testCallback($chars)) return implode("", $chars);
for ($i3 = $i1 + 1; $i3 < $len; ++$i3) {
if ($chars[$i3] != $testChars[$testCharsLen - 1]) {
$i1 = $len;
break 2;
}
}
}
if ($i2 == $testCharsLen) $chars[$i1] = $testChars[0];
}
}
return false;
}
$brut = BruteForce(implode("", $chars), 1, $len, function ($testChars) use($str, &$total) {
$total++;
return strcmp(implode($testChars), $str) == 0;
});
print sprintf("Full string: %s => %d\r\n", $brut, $total);
$total = 0;
$brut = '';
$len = strlen($str);
for($i = 0; $i < $len; $i++){
foreach($chars as $char){
$total++;
if(ord($char) == ord($str[$i])){
$brut .= $char;
continue 2;
}
}
}
print sprintf("By char: %s => %d\r\n", $brut, $total);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.