douzai3399 2015-03-18 17:14
浏览 29
已采纳

通过CSV搜索PHP会错过每行的第一个字符

I'm having a .csv with about a hundred lines, each line looking like this:

lastname, firstname, role, ...

I'm searching through the .csv with the script provided below which works fine.

The only problem is that it returns only matches from the second character of the lastname on. So if I type some firstname -> match, role -> match, astname -> match, lastname -> no match. Obviously the first character of each line is ignored, but I don't know why. Also PHP does not show ä, ö, ü characters but finds them in the .csv.

<?php
//returns an array containing each line as value of another array
$csv = array_map('str_getcsv', file('data.csv'));
//get the search parameter from URL
$q=$_GET["q"];

if(strlen($q) > 0) {
  $hint="";
  foreach($csv as $line){
    //if the line contains the search string, append it to the resulting string
    if(strpos($line[0], $q, 0) != FALSE) {
        $hint = $hint."<p>".$line[0]."</p>";
    }
  }
}

// Set output to "no suggestion" if no hint was found
// or to the correct values
if ($hint == "") {
  $response = "no suggestions";
} else {
  $response = $hint;
}

//output the response
echo $response;
?>
  • 写回答

1条回答 默认 最新

  • dongqin6926 2015-03-18 17:31
    关注

    Solution to: PHP Loose Comparison and strpos Zero Index Problem

    Limit your conditional statement to an exact type comparison, using !==:

    if(strpos($line[0], $q, 0) !== FALSE) {
        $hint = $hint."<p>".$line[0]."</p>";
    }
    

    PHP strpos uses a zero-based string index, so it's actually matching lastname at position 0 and returns that value, which is loosely interpreted as FALSE. However, using a strict type comparison, such as === and !== limits your conditional statement to look for a match of type (boolean in this case) and value.

    In the olden days of programming (when typewriters were used) I resorted to this hack: strpos("_".$string, $match).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么