【问题标题】:PHP not comparing with arraypartPHP不与arraypart比较
【发布时间】:2026-01-20 10:55:02
【问题描述】:

我正在创建一个简单的脚本,它通过文本文件搜索正确的组合,但它不起作用。我排除了所有问题,但所有部分都正常工作,但整个脚本仍然无法正常工作,我不知道如何修复它。

代码:

<html>

<form>
<input type="text" name="input" placeholder="hash"><button type="submit">Crack!</button>
</form>
<?php
$input = $_GET["input"]; // pulling input from url

$hashes = file_get_contents("hashes.txt"); // loading hashes

$hasharray = explode(";", $hashes); // separating hashcombos

$arraynum = count($hasharray); // counting number of hashcombos

// defining loop
$loopnum = 0;
while($loopnum < $arraynum) {
    $combo = $hasharray[$loopnum]; // selecting hashcombo
    $comboarray = explode("|", $combo); // separating hashcombo
    $text = $comboarray[0];
    $hash = $comboarray[1];

    // cecking if hash matches
    if($hash === $input) {
        echo("Hash: $hash");
        echo("<br>");
        echo("Text: $text");
    }

    $loopnum = $loopnum + 1; // updating loop

}
?>
</html>

示例 hashes.txt:

test|example;
example|test;

【问题讨论】:

  • 你得到什么错误信息?
  • 没有错误,在网站上也没有在错误日志中提及
  • 你能分享一个文件 hashes.txt 的样本吗?
  • 尝试使用$_POST而不是$_GET
  • 你没有提供足够的信息,hashes.txt 中有什么内容?我建议您逐行调试,使用var_dump 方法检查您是否获得了正确的数据。您的代码中似乎存在逻辑错误。

标签: php arrays if-statement comparison file-get-contents


【解决方案1】:

您的文件包含换行符,它们也是不可见的字符。例如:

test|example;(newline here)
example|test;

您使用; 拆分文件中的行,但这不会删除换行符。考虑到问题中的 cmets,结果中有换行符导致比较失败。也就是说,我建议在加载哈希以删除换行符后立即使用以下解决方案:

$hashes = preg_replace("/[\r\n]/", "", $hashes);

这将产生如下字符串:

test|example;example|test;

您的其余代码将按预期工作。

【讨论】: