Php 删除包含某些特定字符的行
我想删除包含Php 删除包含某些特定字符的行,php,html,Php,Html,我想删除包含--和~ 代码如下: function removeUnusedLines($string){ if (strpos($string,'--') > 0 || strpos($string,'~') > 0 ) { $string = preg_replace( "/\r|\n/", "", $string ); return $string; } } $file = "C:/AppServ/www/kbbi/try.txt"
--
和~
代码如下:
function removeUnusedLines($string){
if (strpos($string,'--') > 0 || strpos($string,'~') > 0 ) {
$string = preg_replace( "/\r|\n/", "", $string );
return $string;
}
}
$file = "C:/AppServ/www/kbbi/try.txt";
$lines = file($file);
foreach ($lines as $line){
$remove = removeUnusedLines($line);
echo $remove.'<br>';
}
从示例中,我只想得到最后一行,因为第一行和第二行由~
和--
但它并没有消除这条线。请帮帮我,谢谢:)用你的sintax,你抓不到以-,和开头的字符串~ 据 返回针相对于干草堆字符串开头的位置(与偏移无关)。还要注意,字符串位置从0开始,而不是从1开始。
如果未找到针,则返回FALSE 您必须还原条件:),如果未找到,请返回字符串。您要查找的:
您只需使用preg_replace:
$string = preg_replace( '/.*(--|~).*[\r]?[\n]?/', '', $string);
因此,它在一行中查找所有内容,然后是-
或~
,然后是该行中的所有内容*
。可选后跟回车符\r
和/或新行\n
str_replace(数组('--','~'),'$string)代码>?@Darren我想删除行,而不是字符你能告诉我们文本文件的样子吗?@Darren我已经添加了:)
function removeUnusedLines($string){
if (strpos($string,'--') === FALSE && strpos($string,'~') === FALSE ) {
$string = preg_replace( "/\r|\n/", "", $string );
return $string;
}
}
$lines = preg_grep('/--|~/', file($file), PREG_GREP_INVERT);
$string = preg_replace( '/.*(--|~).*[\r]?[\n]?/', '', $string);