douhan1860 2015-12-26 09:36
浏览 21

无法使用PHP正则表达式匹配

I have some PHP code that accepts an uploaded file from an HTML form then reads through it using regex to look for specific lines (in the case below, those with "Number" followed by an integer).

The regex matches the integers like I want it to, but of course they're returned as strings in $matches. I need to check if the integer is between 0 and 9 but I um unable to do this no matter what I try.

Using intval() or (int) to first convert the matches to integers always returns 0 even though the given string contains only integers. And using in_array to compare the integer to an array of 0-9 as strings always returns false as well for some reason. Here's the trouble code...

$myFile = file($myFileTmp, FILE_IGNORE_NEW_LINES);
$numLines = count($myFile) - 1;
$matches = array(); 
$nums = array('0','1','2','3','4','5','6','7','8','9');
for ($i=0; $i < $numLines; $i++) {
    $line = trim($myFile[$i]);
    $numberMatch = preg_match('/Number(.*)/', $line, $matches);
    if ($numberMatch == 1 and ctype_space($matches[1]) == False) { // works up to here
       $number = trim($matches[1]); // string containing an integer only
       echo(intval($number)); // conversion doesn't work - returns 0 regardless
       if (in_array($number,$nums)) { // searching in array doesn't work - returns FALSE regardless
          $number = "0" . $number;
       }
    }
}

I've tried type checking, double quotes, single quotes, trimming whitespace, UTF8 encoding...what else could it possibly be? I'm about to give up on this app entirely, please save me.

  • 写回答

2条回答 默认 最新

  • dongtan2017 2015-12-26 09:42
    关注

    Use '===' for eq for example

    if 1 == '1' then true;
    if 1 === '1' false;
    if 1 == true then true;
    if 1 === true then false
    

    You can show file?

    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效