#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    15
    Rep Power
    0

    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?

    Thanks,
    Tom
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,965
    Rep Power
    9397
    preg_match.

    Do you have shell access? In other words what does
    PHP Code:
    echo `grep -l "echo" .`; 
    output?
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    15
    Rep Power
    0
    Originally Posted by requinix
    preg_match.

    Do you have shell access? In other words what does
    PHP Code:
    echo `grep -l "echo" .`; 
    output?
    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)

    Thanks,
    Tom
  6. #4
  7. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    Hi,

    the function reference at php.net should answer your questions.
  8. #5
  9. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,846
    Rep Power
    6351
    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:

    PHP Code:
    $matches preg_grep('/' preg_quote($SearchTerm) . '/'file($FilePath)); 
    There's probably a better solution to whatever problem you're trying to solve.
    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.

IMN logo majestic logo threadwatch logo seochat tools logo