PHP,从包含特定单词的大字符串中删除所有行

Kri*_*eth 3 php pattern-matching

$file = file_get_contents("http://www.bigsite.com");
Run Code Online (Sandbox Code Playgroud)

我怎样才能从$file包含单词"hello"的字符串中删除所有行?

小智 10

$file = file_get_contents("http://www.bigsite.com");
$lines = explode("\n", $file);
$exclude = array();
foreach ($lines as $line) {
    if (strpos($line, 'hello') !== FALSE) {
         continue;
    }
    $exclude[] = $line;
}
echo implode("\n", $exclude);
Run Code Online (Sandbox Code Playgroud)

  • 如果你使用 `file` 而不是 `file_get_contents`,你可以跳过整个过程两次(一次是将它读入一个字符串,另一次是将字符串“分解”为一个数组)。`file` 直接将其读入数组。 (2认同)