8

Guys ( preg_replace gurus );

I am looking for a preg_replace snippet , that i can use in a php file whereby if a word appears in a particular line, that entire line is deleted/replaced with an empty line

pseudocode:

$unwanted_lines=array("word1","word2"."word3");
$new_block_of_lines=preg_replace($unwanted_lines, block_of_lines);

Thanx.

3 Answers 3

8

The expression

First, let's work out the expression you will need to match the array of words:

/(?:word1|word2|word3)/

The (?: ... ) expression creates a group without capturing its contents into a memory location. The words are separated by a pipe symbol, so that it matches either word.

To generate this expression with PHP, you need the following construct:

$unwanted_words = array("word1", "word2", "word3");
$unwanted_words_match = '(?:' . join('|', array_map(function($word) {
    return preg_quote($word, '/');
}, $unwanted_words)) . ')';

You need preg_quote() to generate a valid regular expression from a regular string, unless you're sure that it's valid, e.g. "abc" doesn't need to be quoted.

See also: array_map() preg_quote()

Using an array of lines

You can split the block of text into an array of lines:

$lines = preg_split('/\r?\n/', $block_of_lines);

Then, you can use preg_grep() to filter out the lines that don't match and produce another array:

$wanted_lines = preg_grep("/$unwanted_words_match/", $lines, PREG_GREP_INVERT);

See also: preg_split() preg_grep()

Using a single preg_replace()

To match a whole line containing an unwanted word inside a block of text with multiple lines, you need to use line anchors, like this:

/^.*(?:word1|word2|word3).*$/m

Using the /m modifier, the anchors ^ and $ match the start and end of the line respectively. The .* on both sides "flush" the expression left and right of the matched word.

One thing to note is that $ matches just before the actual line ending character (either \r\n or \n). If you perform replacement using the above expression it will not replace the line endings themselves.

You need to match those extra characters by extending the expression like this:

/^.*(?:word1|word2|word3).*$(?:\r\n|\n)?/m

I've added (?:\r\n|\n)? behind the $ anchor to match the optional line ending. This is the final code to perform the replacement:

$replace_match = '/^.*' . $unwanted_words_match . '.*$(?:\r\n|\n)?/m';
$result = preg_replace($replace_match, '', $block_of_lines);

Demo

6
  • 1
    @HamZa The \n is always there, sometimes preceded by \r :) there might be performance considerations.
    – Ja͢ck
    Jul 4, 2013 at 9:29
  • @Jack - couldnt use your code as i could not understand what is the meaning of a partial regular expression for $words_re
    – MarcoZen
    Jul 4, 2013 at 11:23
  • and also the part of removing the whole line requires an extra trick ... part.
    – MarcoZen
    Jul 4, 2013 at 11:24
  • @MarcoZen I can elaborate my answer if that's what you mean :) give me a while.
    – Ja͢ck
    Jul 4, 2013 at 12:00
  • @Jack - That will be great. Thanx. Also is there a way i can use DevZero one liner $newstring = preg_replace("/^.*word1.*$/", "", $string) into some kind of for loop and make it remove the lines as it goes through an array ?
    – MarcoZen
    Jul 5, 2013 at 0:38
1

This regular expression can remove the match from a line

$newstring = preg_replace("/^.*word1.*$/", "", $string);
2
  • @DevZero, does this remove the entire line if the word appears or just the word from the line ?
    – MarcoZen
    Jul 4, 2013 at 11:34
  • this removes the entire line
    – DevZer0
    Aug 12, 2015 at 0:18
1

As @jack pointed out, let's just use preg_quote() && array_map()

$array = array('word1', 'word2', 'word3', 'word#4', 'word|4');
$text = 'This is some random data1
This is some word1 random data2
This is some word2 random data3
This is some random data4
This is some word#4 random data5
This is some word|4 random data6
This is some word3 random data7'; // Some data

$array = array_map(function($v){
    return preg_quote($v, '#');
}, $array); // Escape it
$regex = '#^.*('. implode('|', $array) .').*$#m'; // construct our regex
$output = preg_replace($regex, '', $text); // remove lines
echo $output; // output

Online demo

11
  • 1
    Fails for words with # in them, such as "word#4".
    – Ja͢ck
    Jul 4, 2013 at 9:22
  • 1
    Now it does funny stuff when you have "word|4" =D
    – Ja͢ck
    Jul 4, 2013 at 9:28
  • Hamza - Jack - u guys buddies ? :)
    – MarcoZen
    Jul 4, 2013 at 9:38
  • You should have realized by now that using preg_quote() is the only way out :)
    – Ja͢ck
    Jul 4, 2013 at 9:42
  • 1
    You can't escape your destiny ;-)
    – Ja͢ck
    Jul 4, 2013 at 9:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.