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

时间:2013-03-02 02:03:59

标签: php pattern-matching

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

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

3 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分: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);

答案 2 :(得分:1)

你走了:

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

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

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