首页 > 解决方案 > PHP字符串比较到一个txt

问题描述

$search是由表单中的文本输入组成的变量字符串。我正在查看是否在 txt 文件中找到了该字符串。我认为我的正则表达式有问题,但我不确定。

文本文件的现有条目将如下所示Title%Author%ISBN%Publisher%Year

我的问题是,当我提交表单时,它会进入一个空白页面。

    elseif ($inquiry=='search') {

        $file= fopen("database.txt", "r") or die("File was not found on server"); 

        $search =  "/^[$Title."%".$Author."%".$ISBN."%".$Publisher."%".$Year]/i";

        //search function
        // What to look for

        // open and Read from file
        $lines = file('database.txt');//array

        foreach($lines as $line) {
            // Check if the line contains the string we're looking for, and print if it does
            if(preg_match($search, $line)) {
                echo $line;
            } else {
                echo "Search not found";
            }
        }
    }

    fclose($file);
}

标签: php

解决方案


你首先要知道两件事。

PHP 中的特殊$字符用于命名变量。

当您在双引号字符串中注入带有前缀的单词时$,这将被视为变量名,并且变量会尝试扩展自身。

我之所以提到这一点是因为这一行:

$search =  "/^[$Title."%".$Author."%".$ISBN."%".$Publisher."%".$Year]/i";

所以,我最好的猜测是你正在尝试使用和扩展变量名。所以,如果是这样的话,你的意图是可以的。

但请注意,您在 Title 之后有一个不匹配且未关闭的 "。

还要记住,$在正则表达式中具有特殊含义,它们通常用于尝试匹配“行尾”。

注意:您的脚本可能由于标题后缺少“而死”。


推荐阅读