我正在编写一个代码,用于为我的搜索引擎索引单词。类似的东西:
$handle = fopen("http://localhost/ps-friend/index.php", "r");
while( $buf = fgets($handle,1024) )
{
/* Remove whitespace from beginning and end of string: */
$buf = trim($buf);
/* Try to remove all HTML-tags: */
$buf = strip_tags($buf);
$buf = preg_replace('/&\w;/', '', $buf);
/* Extract all words matching the regexp from the current line: */
preg_match_all("/(\b[\w+]+\b)/",$buf,$words);
/* Loop through all words/occurrences and insert them into the database(Not shown here): */
for( $i = 0; $words[$i]; $i++ )
{
for( $j = 0; $words[$i][$j]; $j++ )
{
$cur_word = addslashes( strtolower($words[$i][$j]) );
echo $cur_word;
}
}
}
当我回复$cur_word
为什么我一直收到错误Notice: Undefined offset: 2 in C:\xampp\htdocs\ps-friend\search.php on line 26
,有时收到line 24
。纠正它的方法是什么?
答案 0 :(得分:4)
你for-loop看起来有点奇怪。我想你想要的是:
for( $i = 0; $i < count($words); $i++ )
{
答案 1 :(得分:2)
for( $i = 0; $i < count($words); $i++ )
{
for( $j = 0; $j < count($words[$i]); $j++ )
您的代码正在直接测试$words[$i]
。但这意味着循环在到达不存在的元素时结束,这会导致警告,因为您尝试引用它。
如果您这样做,您的结构就可以了:
for( $i = 0; isset($words[$i]); $i++ )
{
for( $j = 0; isset($words[$i][$j]); $j++ )
isset()
测试变量是否存在,并且不会发出警告。