【问题标题】:line brek error with search system in phpphp中搜索系统的换行错误
【发布时间】:2015-01-23 03:28:41
【问题描述】:

我正在开发一个系统来搜索用户在 php 文件中键入的单词,使用没有 MySQL 的 PHP,但我遇到了问题。当文件中没有换行符时,系统运行良好。例如,如果我在包含文本“早上好”的文件中搜索“好”这个词可以正常工作,但如果我在包含文本“好
morning”的文件中搜索“好”(使用换行符)它不会因此列出文件。这是我的代码:
index.php

<form action="busca.php" method="get">
<input type="text" name="s"><br>
<input type="submit">
</form>

busca.php

<?php
$pesq = (isset($_GET['s'])) ? trim($_GET['s']) : '';
if (empty($pesq)) {
    echo 'Type something.';
} else {
    $index    = "index.php";
    $busca    = glob("posts/content/*.php", GLOB_BRACE);
    $lendo    = "";
    $conteudo = "";
    foreach ($busca as $item) {
        if ($item !== $index) {
            $abrir = fopen($item, "r");
            while (!feof($abrir)) {
                $lendo = fgets($abrir);
                $conteudo .= $lendo;
                $lendo .= strip_tags($lendo);
            }
            if (stristr($lendo, $pesq) == true) {
                $dados    = str_replace(".php", "", $item);
                $dados    = basename($dados);
                $result[] = "<a href=\"posts/$dados.php\">$dados</a>";
                unset($dados);
            }
            fclose($abrir);
        }
    }
    if (isset($result) && count($result) > 0) {
        $result = array_unique($result);
        echo '<ul>';
        foreach ($result as $link) {
            echo "<li>$link</li>";
        }
        echo '</ul>';
    } else {
        echo 'No results';
    }
}
?>

【问题讨论】:

  • 这是错误的:$lendo .= strip_tags($lendo);。应该是$lendo = strip_tags($lendo);。当您可以使用 file_get_contents() 轻松将文件加载到变量中时,为什么还要为循环而烦恼?
  • 我应该在哪里使用 file_get_contents()?我猜循环是搜索所必需的
  • 请看我的回答

标签: php search system


【解决方案1】:

您对stristr 的使用不正确。
将其与 false 进行比较,如下所示:

if (stristr($lendo, $pesq) !== false) {

如果找到一个字符串——函数返回子字符串。可以转换为布尔值truefalse,你永远不知道。如果它没有找到它——它返回false——你应该比较它的唯一正确值。

为此使用strpos 更好。
我的变种:

foreach ($busca as $item) {
        if ($item !== $index) {
            $lendo = file_get_contents($item);
            $lendo = strip_tags($lendo);
            if (strpos($lendo, $pesq) !== false) {
                $dados    = str_replace(".php", "", basename($item));
                $result[] = "<a href=\"posts/$dados.php\">$dados</a>";
            }
        }
    }

要修复换行符 - 尝试摆脱它们 像这样:

$lendo = file_get_contents($item);
$lendo = strip_tags($lendo);
$lendo = str_replace(["\r","\n"], ' ', $lendo);

【讨论】:

  • 不错的提示,但它仍然不适用于换行符
  • 再次检查代码。看看你在循环中做了什么: ` $lendo = fgets($abrir);` 你用每一行代码替换了 $lendo。不是添加而是替换。在while 的末尾,它将包含最后一行only。这也是为什么最好使用file_get_contents 的原因。添加这样的错误的机会更少
猜你喜欢
  • 2011-01-14
  • 2013-03-09
  • 1970-01-01
  • 2014-02-17
  • 1970-01-01
  • 2017-11-25
  • 2011-10-22
  • 2012-07-16
  • 1970-01-01
相关资源
最近更新 更多