$file = file_get_contents("http://www.bigsite.com");
我该如何从字符串
$file
中删除所有包含单词“hello”的行?$file = file_get_contents("http://www.bigsite.com");
$file
中删除所有包含单词“hello”的行?$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
,你可以跳过二次处理整个文件(一次读入到字符串中,另一次将字符串 explode
成数组)。file
直接将其读入数组中。 - Jonathan Wren$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);
strpos
只能找到一个单词,你可以用正则表达式匹配多个单词。 - Madan Sapkota这里是您需要的:
$file = file('http://www.bigsite.com');
foreach( $file as $key=>$line ) {
if( false !== strpos($line, 'hello') ) {
unset $file[$key];
}
}
$file = implode("\n", $file);
$file = file_get_contents("http://www.bigsite.com");
echo preg_replace('/((^|\n).*hello.*(\n|$))/', "\n", $file).trim();
这4个模式是用于匹配的
如果这些是带有\r\n(回车和换行符,如Windows)的文件,则需要相应地进行修改。Trim可以删除尾随和/或前导换行符