Extract string matching phrase

I want to combine the whole line corresponding to the word / phrase on this line! I tried this:

preg_match("/PHRASE/i", $dictionary,$matches); 

But I get only a matching word! but I need this whole line! And there are more than 15K lines!

0
php regex
source share
3 answers

Just use

 ^.*PHRASE.*$ 

^ to match the beginning of a line

.* to match any number of characters except newlines

PHRASE according to your keyword / phrase

.* as above

$ to match end of line.

You can also surround your PHRASE anchors of the word boundary (if your phrase is really a word or words): ^.*\bPHRASE\b.*$ Will only match if PHRASE is independent (and not part of another word like PHRASEBOOK ).

So, if you apply your regular expression to each individual line separately, use

 preg_match('/^.*PHRASE.*$/i', $dictionary, $matches) 

If you have all your lines inside a long multi-line line and you want to iterate over all lines containing your phrase, use:

 preg_match_all('/^.*PHRASE.*$/im', $dictionary, $matches, PREG_PATTERN_ORDER); for ($i = 0; $i < count($matches[0]); $i++) { # Matched text = $matches[0][$i]; } 

Note the /m modifier to allow ^ and $ match at the beginning and end of each line (instead of the beginning / end of the line).

+4
source share

Use something like:

 $handle = @fopen("file.txt", "r"); if ($handle) { $matches = array(); while (!feof($handle)) { $buffer = fgets($handle); if(stripos($buffer,"mystring") !== false) { $matches[] = $buffer; } } fclose($handle); } 

Then you can see the results in $matches

+3
source share

try

 preg_grep('/whatever/', file('filename')); 

file - Reads the entire file into an array

preg_grep - return array entries matching the pattern

+1
source share

All Articles