November 5th, 2012, 08:06 PM
How to use preg_grep to find string in a file
Can I use preg_grep to search a file to see if it contains a string?
I have an array of strings that I want to loop through and test the each string against a file to see if there is a match within the file. Could someone give me the correct syntax for the preg_grep?
November 5th, 2012, 08:37 PM
Do you have shell access? In other words what does
echo `grep -l "echo" .`;
November 6th, 2012, 05:23 AM
The situation is I have two variables, $FilePath and $SearchTerm and the question is what is the syntax to use preg_grep to search $FilePath for the SearchTerm and if a match is found what is the value returned (true, false, the string found)
Originally Posted by requinix
November 6th, 2012, 05:44 AM
November 6th, 2012, 08:25 AM
preg_grep doesn't search files. As it says in the manual, it searches arrays.
There is another function which turns a file INTO an array, but if the file is particularly large, that may overload PHP's memory:
There's probably a better solution to whatever problem you're trying to solve.
$matches = preg_grep('/' . preg_quote($SearchTerm) . '/', file($FilePath));
HEY! YOU! Read the New User Guide and Forum Rules
"They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin
"The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002
Think we're being rude? Maybe you asked a bad question
or you're a Help Vampire.
Trying to argue intelligently? Please read this.