Reputation: 15934
I need to try and strip out lines in a text file that match a pattern something like this:
anything SEARCHTEXT;anything;anything
where SEARCHTEXT will always be a static value and each line ends with a line break. Any chance someone could help with the regext for this please? Or give me some ideas on where to start (been to many years since I looked at regex).
I am planning on using PHP's preg_replace() for this.
Thanks.
Upvotes: 2
Views: 2182
Reputation: 34395
This solution removes all lines in $text
which contain the sub-string SEARCHTEXT
:
$text = preg_replace('/^.*?SEARCHTEXT.*\n?/m', '', $text);
My benchmark tests indicate that this solution is more than 10 times faster than '/\n?.*SEARCHTEXT.*$/m'
(and this one correctly handles the case where the first line matches and the second one doesn't).
Upvotes: 5
Reputation: 25582
Use a regex to match the whole line like so:
^.*SEARCHTEXT.*$
preg_replace
would be a good option for this.
$str = preg_replace('/\n?.*SEARCHTEXT.*$/m', '', $str);
The \n
escape matches the line break for the matched line. This way matched lines are removed and the replace method does not just leave empty lines in the string.
The /m
flag makes the caret (^
) match the start of each line instead of the start of the string.
Upvotes: 2