Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 删除包含某些特定字符的行_Php_Html - Fatal编程技术网

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