Reputation: 49
I wanna remove line of txt file that contain --
and ~
here's the code :
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>';
}
example :
Poetry is a form of literature ~ that uses aesthetic and rhythmic
qualities of language —- such as phonaesthetics, sound symbolism
metre to evoke meanings in addition to, or in place of, the prosaic ostensible meaning
From example, I wanna get just the last because the first and the second line consist ~
and --
but it doesnt remove the line. help me please, thank you :)
Upvotes: 0
Views: 63
Reputation: 11832
You can just use preg_replace:
$string = preg_replace( '/.*(--|~).*[\r]?[\n]?/', '', $string);
So it looks for everyting on one line .*
, followed by either --
or ~
, followed again by everything on that line .*
. Optionally followed by carriage return \r
and/or new line \n
.
Upvotes: 0
Reputation: 215049
You're looking for preg_grep
:
$lines = preg_grep('/--|~/', file($file), PREG_GREP_INVERT);
Upvotes: 1
Reputation: 72
with your sintax you don't catch string who begin with -- and ~
according to strpos documentation
Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
function removeUnusedLines($string){
if (strpos($string,'--') === FALSE && strpos($string,'~') === FALSE ) {
$string = preg_replace( "/\r|\n/", "", $string );
return $string;
}
}
You must revert condition :) if not found return the string.
Upvotes: 0