Search code examples
phpsubstrstrpos

strpos() returning seemingly random values


I am trying to extract bits of a string.

The string looks like this:

$rowstr = "8:12-bk-16430|8:2012-bk-16430|1080751|7|||||10/30/2012|1/30/2012|||bk|||PINELLAS-FL|Tampa|Paid...

I get the first field just fine using this:

$pos1 = strpos($rowstr, "|") +1; //begining of field case number
$pos2 = strpos($rowstr, "|", $pos1 + 1); //end of field case number
$len1 = $pos2 - $pos1;  //string length
$field['case_num'][$i] = substr($rowstr,$pos1,$len1); // casenumber extracted

But when I try to extract the second field (should be 1080751)

$pos3 = strpos($rowstr, "|", $pos2); //end of field 
$pos4 = strpos($rowstr, "|", $pos3 + 1); //end of field
$len2 = $pos3 - $pos4;  //string length
$field['field2'][$i] = substr($rowstr,$pos3,$len2); // field 2 extracted

The result is a very long string that starts with |1080751|7|||||10/30/2012|10...

If $pos3 returns 16 and $pos4 returns 24 then why am I getting a result so much longer than 8 characters? Is PHP not counting special charters for some reason? How can I fix this?


Solution

  • Try

    // Added + 1 here
    $pos3 = strpos($rowstr, "|", $pos2) + 1; //end of field
    $pos4 = strpos($rowstr, "|", $pos3 + 1); //end of field
    // swapped $pos3 and $pos4 here
    $len2 = $pos4 - $pos3;  //string length
    $field['field2'][$i] = substr($rowstr,$pos3,$len2); // field 2 extracted