Array_Search总是从file_get_contents php返回false

时间:2018-03-28 16:38:01

标签: php

我有一个文本文件,包含以下内容和其他一些内容,但我已经在这里省略了它们

###Sprint-Name###
SPRINT 20180403
###DEV-Number###
DEV-1039
###Functionality###
To do a thing

该文件是通过表格

上传的

我的代码如下:

<?php
//Import the errorhandler
include_once('errorHandler.php');

//First of all, we need to get the contents of the test document so that we can process it
//The test document needs to be exploded based on newline
$testDocument = explode(PHP_EOL, file_get_contents($_FILES['testDocument']['tmp_name']));

echo '<pre>';
    var_dump(array_search("###Sprint-Name###", $testDocument));
    print_r($_POST);
    print_r($_FILES);
    print_r($testDocument);
echo '</pre>';
?>

但var转储正在返回bool(false),即使我的$testDocument数组是:

Array
(
    [0] => ###Sprint-Name###
    [1] => QA Reporting
    [2] => ###Dev-Number###
    [3] => DEV-1231
    [4] => ###Functionality###
    [5] => To do a thing
)

如果数组$ testDocument被强制为:

$testDocument = array("thing","###Sprint-Name###","other");

然后返回1,这是正确的,因为针在大海捞针处是1

也许它与###上的编码有关,我该如何检查,以及如何强制它进行特定编码?感谢。

编辑:我尝试从字符串中删除###并使用不同的字符,以防PHP认为它们是评论或其他内容,但这没有效果。

1 个答案:

答案 0 :(得分:0)

您的问题是PHP_EOL分裂/爆炸 如果文件是在与执行文件不同的系统上创建的,则PHP_EOL可能无法捕获正确的或所有新行的回车符。这会产生一个值,在您的情况下会留下尾随\r 见这里:

var_dump($testDocument[0]);
//output: 
// string(18) "###Sprint-Name### "
// trailing character at the end

所以,要解决这个问题,你可以做一个preg_slit,你可以用它来分割几个字符:

<?php

$input = <<<EOT
###Sprint-Name###
SPRINT 20180403
###DEV-Number###
DEV-1039
###Functionality###
To do a thing
EOT;

$testDocument = preg_split("/[\r\n]+/", $input);

var_dump($testDocument);

$key = array_search("###Sprint-Name###", $testDocument);
var_dump($key); // int(0)

或者使用file代替file_get_contents,正如@CBroe推荐的那样。