【问题标题】:Php while inside for - What's wrong with this code?PHP while inside for - 这段代码有什么问题?
【发布时间】:2016-12-04 17:10:20
【问题描述】:

此代码用于读取包含 100 个 url 的文本文件的内容,每行一个。该脚本是使用 file_get_contents 在 url 中搜索特定单词。

<?php  
$mysearch = file("phpelist.txt");  

for($index = 0; $index <count($mysearch); $index++)  
{  while ($index >=10 && $index <=20 ):

    $mysearch[$index] = str_replace("\n", "", $mysearch[$index]);  
    $data = file_get_contents("$mysearch[$index]");  

    $searchTerm = 'about';  

    if (stripos($data, $searchTerm) !== false) {
        echo "$mysearch[$index]</strong>...FOUND WORD<br><strong>";  
    } 
    else 
    {  
        echo "$mysearch[$index]</strong>...NO SUCH WORD<br><strong>";  
    }  
 endwhile;
} 

?>

【问题讨论】:

  • $indexwhile 内部没有修改,一旦进入就永远不会退出
  • 你确定这段代码可以运行吗?看起来你那里有语法错误......使用endwhile时,你应该使用while(...) :
  • 并阅读其他评论:)
  • 也许您想要的是if 而不是while?无论如何,语法是错误的,就像上面提到的那样 - php.net/manual/en/control-structures.while.php
  • 嗨,我将 while 更改为 if 并显示所有网址。我需要 10 到 20 之间的行。

标签: php while-loop


【解决方案1】:

你的代码让我很困惑。只看需求声明,我得到了......

$searchTerm = 'about';
$file = new SplFileObject('phpelist.txt');
foreach ($file as $n => $url) {
    if ($n < 10) continue;
    if ($n > 20) break;

    $content = file_get_contents($url);
    if (stripos($content, $searchTerm) !== false) {
        echo "<strong>$url</strong>...FOUND WORD<br>";
    } else {
        echo "<strong>$url</strong>...NO SUCH WORD<br>";
    }
}

更正:附加要求(参见下面的 cmets)。这意味着它不再比 OP 短。我猜它唯一增加的就是SplFileObject的使用。我喜欢使用SplFileObject,因为它允许您使用像数组这样的文件(无需将整个文件加载到内存中),因此可以在foreach 中使用(因为SplFileObject 实现了Iterator 接口)。

【讨论】:

  • 嗨,我需要脚本来读取 10 到 20 之间的行。抱歉没有提及。
  • 我现在也刚刚意识到您不是在 URL 中搜索,而是从该 URL 检索到的内容。让我解决它...
猜你喜欢
  • 2015-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
  • 2018-09-09
相关资源
最近更新 更多