$ target是一个char,我试图在$ line中找到该char的最后一次出现。即使我确定在一些索引的$ line内确实存在$ target,我的每个输出都得-1。
$fh = fopen($someFile, "r");
while (!feof($fh)) {
$test = fgets($fh);
$words = explode(",", $test);
$line = $words[0];
$target = $words[1];
$answer = strrpos($line, $target);
if ($answer !== false) {
echo $answer;
}
else echo -1;
echo "\n";
}
此代码为每个值返回-1。如果我在strrpos函数中将$ line更改为$ test,它每次都可以找到索引。我检查了$ line以确保它不是空的,它实际上是字符串的第一部分。为什么这不起作用?
答案 0 :(得分:0)
我不知道我是否正确理解了你的答案...但是,你的代码中有一些错误:
1)你没有将strrpos的结果分配给$ answer(可能只是一个错字......) 2)你测试函数结果为-1,但如果没有找到匹配,则该函数返回FALSE。
这应该有效:
<?php
$someFile = "data";
$fh = fopen($someFile, "r");
while (!feof($fh)) {
$test = fgets($fh);
$words = explode(",", $test);
$line = $words[0];
$target = $words[1];
$answer = strrpos($line, $target);
if ($answer !== FALSE) {
echo $answer;
} else {
echo -1;
}
echo "\n";
}
?>
使用此数据文件:
haystack,stack,
此代码打印:
3
这应该是你正在寻找的答案......
在开始制作之前(:-)你也应该意识到:
<强> 更新 强>
为了更好地反映您的用例(我希望),并实现我在评论中写的所有建议,这里是 workinkg 代码的更新版本。如果仍然不适合您,请发布您的数据......
文件“ test.php ”:
<?php
$someFile = "data";
$fh = fopen($someFile, "r");
while (1) {
$test = fgets($fh);
if (feof($fh)) break;
$test = chop($test);
$words = explode(",", $test);
$line = $words[0];
$target = $words[1];
$answer = strrpos($line, $target);
if ($answer !== FALSE) {
echo $answer;
} else {
echo -1;
}
echo "\n";
}
?>
文件“数据”:
haystack,s
运行:
$ php test.php
3
答案 1 :(得分:0)
目前还不清楚你在问什么。爆炸不会将第二个元素放在第一个元素中,就像你在问题中提出的那样。同样在您的问题中,您评估了$answer
中的if()
,但是您没有在显示给我们的代码中的任何位置设置$answer
。
但只是为了澄清:
$string = "abcd,efghij,kl";
$array = explode(",",$string);
echo $array[0]; // abcd
echo $array[1]; // efghij
echo $array[2]; // kl
如果您需要了解任何元素的大小,或者下一个元素的开始时间,请使用strlen()
:
echo strleng($array[0]); // 4
echo strleng($array[1]); // 6
echo strleng($array[2]); // 2
由于$array[0]
长度为4个字符,我们后面有逗号,$array[1]
从索引4 + 1 = 5开始。
$array[2]
从索引12开始,因为带有2个逗号的前2个元素是4 + 1 + 6 + 1 = 12。