strpos()返回看似随机的值

时间:2012-10-31 06:02:44

标签: php substr strpos

我正在尝试提取字符串的位。

字符串如下所示:

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

我用第一个字段就可以了:

$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

但是当我尝试提取第二个字段(应该是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

结果是一个以|1080751|7|||||10/30/2012|10..开头的非常长的字符串。

如果$pos3返回16$pos4返回24,那为什么我得到的结果比8个字符长得多?由于某种原因,PHP不计算特殊包机吗?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

尝试

// 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