Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:在数组元素中搜索精确的字符串模式_Php_Regex_Foreach - Fatal编程技术网

PHP:在数组元素中搜索精确的字符串模式

PHP:在数组元素中搜索精确的字符串模式,php,regex,foreach,Php,Regex,Foreach,我想验证通过PHP上传到我网站上的所有文件。我正在使用正则表达式来比较文件内容,但它似乎不像我预期的那样工作。我想接受每行只有一个术语的文件 EXPECTED INPUT: HP34930 HP09099 HP98899 UNACCEPTABLE INPUT: HP89980 HP98798 HP09232 some other text HP58089 这是我的密码: $texthandle = file($_FILES["textfile"]["tmp_name"]); foreach

我想验证通过PHP上传到我网站上的所有文件。我正在使用正则表达式来比较文件内容,但它似乎不像我预期的那样工作。我想接受每行只有一个术语的文件

EXPECTED INPUT:
HP34930
HP09099
HP98899

UNACCEPTABLE INPUT:
HP89980 HP98798 HP09232
some other text
HP58089
这是我的密码:

$texthandle = file($_FILES["textfile"]["tmp_name"]);
foreach ($texthandle as $textline)
{
    if (!preg_match("/(HP\d+){1}/", $textline))
    {
    echo "Incorrect file format. Please provide a text file with 1 term per line.";
            exit(0);
    }       
}
有人能告诉我为什么这不是我想要的方式吗

我也试过了

if (!preg_match("/^(HP\d+){1}$/", $textline))
但它没有像我期望的那样工作


谢谢你的帮助

不确定什么不起作用,但请尝试:

$texthandle = file($_FILES["textfile"]["tmp_name"], FILE_IGNORE_NEW_LINES);
然后:

if (!preg_match("/^HP\d+$/", $textline))
或者,如果只允许5位数字:

if (!preg_match("/^HP[\d]{5}$/", $textline))

如果结尾有空格、制表符等空格,则会失败,因此您可以尝试在$textline上使用trim()。

“不起作用”不是正确的问题解释。以及“工作不正常”。只有你知道“正确”是什么意思。我做了一些编辑,以减少歧义。我希望这会有帮助。我接受了你的代码,它确实有效@Mike W:整个文件都无效。OP逐行检查,结果是整个文件是否良好。您的正则表达式(通过行为)与OP的正则表达式相同。区别在于
^
$
字符;它们分别检查线路的起点和终点。@Ed Cottrell:第二个OP中有锚attempt@zerkms:可能工作方式相同,也可能不相同,但绝对不相同:)而且,可能不是正则表达式?@AbraCadaver:它与问题中的
/^(HP\d+{1}$/
相同。如果你看到你的和这个之间的差异-请分享。