I have a text file and I want to remove some lines that contain specific words
<?php
// set source file name and path
$source = "problem.txt";
// read raw text as array
$raw = file($source) or die("Cannot read file");
now there’s array from which I want to remove some lines and want to use them so on.
As you have each line of your file in a row of an array, the
array_filterfunction might interest you (quoting) :And you can use
strposorstriposto determine if a string is contained in another one.For instance, let’s suppose we have this array :
We could define a callback function that would filter out lines containing “
glop” :And use that function with
array_filter:And we’d get this kind of output :
i.e. we have removed all the lines containing the “badword” “glop”.
Of course, now that you have the basic idea, nothing prevents you from using a more complex callback function 😉
Edit after comments : here’s a full portion of code that should work :
First of all, you have your list of lines :
Then, you load the list of bad words from a file :
And you trim each line, and remove empty lines, to make sure you only end up with “words” in the
$bad_wordsarray, and not blank stuff that would cause troubles.The
$bad_wordsarray contains, from my test file :Then, the callback function, that loops over that array of bad words:
Note : using a global variable is not that nice 🙁 But the callback function called by
array_filterdoesn’t get any other parameter, and I didn’t want to load the file each time the callback function is called.And, as before, you can use
array_filterto filter the lines :Which, this time, gives you :