$file = file_get_contents("http://www.bigsite.com");
我怎么能去掉字符串$file
中包含单词“hello”的所有行?PHP,从包含特定单词的大字符串中删除所有行
$file = file_get_contents("http://www.bigsite.com");
我怎么能去掉字符串$file
中包含单词“hello”的所有行?PHP,从包含特定单词的大字符串中删除所有行
$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);
我需要整个行删除,不仅字。 – 2013-03-02 02:11:46
这实际上只是移除了单词的实例,而不是单词出现的行,因为这个问题需要。 – 2013-03-02 02:13:33
@CodeProtocol来自PHP手册:“如果您只想检查一个字符串是否包含在另一个字符串中,请不要使用preg_match(),因为它们会更快,所以请使用strpos()或strstr()。 (http://php.net/manual/en/function.preg-match.php) – 2013-03-02 02:24:39
$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);
如果使用'file'而不是'file_get_contents',则可以跳过两遍(一次将其读入一个字符串,另一次将'爆炸'到字符串中)。 'file'将它直接读入数组中。 – 2013-03-02 02:30:00
在这里你去:
$file = file('http://www.bigsite.com');
foreach($file as $key=>$line) {
if(false !== strpos($line, 'hello')) {
unset $file[$key];
}
}
$file = implode("\n", $file);
哈哈,是的,但即时通讯问,因为我敢肯定,那里有一个更好的办法,比我在做什么它。是的,有:) – 2013-03-02 02:10:43