PHP,从一个大字符串中删除包含特定词语的所有行。

4
$file = file_get_contents("http://www.bigsite.com");

我该如何从字符串$file中删除所有包含单词“hello”的行?

哈哈,是的,但我问这个问题是因为我相信有比我之前做的更好的方法。而且,确实有更好的方法 :) - Kristian Rafteseth
4个回答

13
$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);

2
如果你使用 file 而不是 file_get_contents,你可以跳过二次处理整个文件(一次读入到字符串中,另一次将字符串 explode 成数组)。file 直接将其读入数组中。 - Jonathan Wren

2
$file = file_get_contents("http://www.example.com");

// remove sigle word hello
echo preg_replace('/(hello)/im', '', $file);

// remove multiple words hello, foo, bar, foobar
echo preg_replace('/(hello|foo|bar|foobar)/im', '', $file);

编辑删除行

// read each file lines in array
$lines = file('http://example.com/');

// match single word hello
$pattern = '/(hello)/im';

// match multiple words hello, foo, bar, foobar
$pattern = '/(hello|foo|bar|foobar)/im';

$rows = array();

foreach ($lines as $key => $value) {
    if (!preg_match($pattern, $value)) {
        // lines not containing hello
        $rows[] = $line;
    }
}

// now create the paragraph again
echo implode("\n", $rows);

我需要整行都被删除,而不仅仅是单词。 - Kristian Rafteseth
实际上,这只是删除了单词的实例,而不是问题所要求的行。 - Jonathan Wren
@CodeProtocol 从PHP手册中得知:"如果你只想检查一个字符串是否包含在另一个字符串中,请不要使用preg_match()。相反,使用strpos()或strstr(),因为它们会更快。" (http://php.net/manual/en/function.preg-match.php) - Jonathan Wren
@Duotrigesimal,我知道。你说话的方式已经被其他人回答了,我不能复制粘贴,这是另一种解决方案。此外,strpos只能找到一个单词,你可以用正则表达式匹配多个单词。 - Madan Sapkota
@CodeProtocol 这很公正。我只是为了社区的利益指出你方法上的缺陷。 - Jonathan Wren

1

这里是您需要的:

$file = file('http://www.bigsite.com');

foreach( $file as $key=>$line ) {
  if( false !== strpos($line, 'hello') ) {
    unset $file[$key];
  }
}

$file = implode("\n", $file);

0
$file = file_get_contents("http://www.bigsite.com");
echo preg_replace('/((^|\n).*hello.*(\n|$))/', "\n", $file).trim();

这4个模式是用于匹配的

  • 如果第一行有hello
  • 中间行有hello
  • 最后一行有hello
  • 唯一的一行有hello

如果这些是带有\r\n(回车和换行符,如Windows)的文件,则需要相应地进行修改。Trim可以删除尾随和/或前导换行符


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接