2013-03-02 123 views

回答

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); 
+0

我需要整个行删除,不仅字。 – 2013-03-02 02:11:46

+0

这实际上只是移除了单词的实例,而不是单词出现的行,因为这个问题需要。 – 2013-03-02 02:13:33

+0

@CodeProtocol来自PHP手册:“如果您只想检查一个字符串是否包含在另一个字符串中,请不要使用preg_match(),因为它们会更快,所以请使用strpos()或strstr()。 (http://php.net/manual/en/function.preg-match.php) – 2013-03-02 02:24:39

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

如果使用'file'而不是'file_get_contents',则可以跳过两遍(一次将其读入一个字符串,另一次将'爆炸'到字符串中)。 'file'将它直接读入数组中。 – 2013-03-02 02:30:00

1

在这里你去:

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

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

$file = implode("\n", $file); 
相关问题