Ugh
Ugh

Reputation: 31

Unable to make use of PHP regex matches

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.

Upvotes: 0

Views: 23

Answers (2)

hakre
hakre

Reputation: 198117

You write in your question that you're using a regular expression to look for the term "Number" followed by a single digit (0-9).

A regular expression for it would be:

/Number(\d)/

It will contain in the matching group 1 the number (digit) you're looking for.

The pattern you use:

/Number(.*)/

can contain anything (but a line-break) in the first matching group. It obviously is matching too much. You then have a problem filtering that too much retro-actively.

It normally works best to first look as precise as possible than to fiddle with too much noise afterwards.

Upvotes: 0

Naumov
Naumov

Reputation: 1167

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?

Upvotes: 1

Related Questions