Jump to content

preg_grep


bigjim

Recommended Posts

I am a student in a Linux class. I need to be able to search for lines within a file for certain text. The script I have written runs but delivers an empty array. I know the /etc/crontab file has the word "test" but I can't seem to get this to work properly. This is not my finished work, I just need to get the preg_grep function working before I can go any further.SCRIPT#! /usr/bin/php<?php fwrite(STDOUT, "Enter the name of the file you wish to open \n");$file = array(trim(fgets(STDIN)));$grepfile = preg_grep ( "/test/" , $file );print_r($grepfile);?>OUTPUTbigjim3@bigjim3-desktop:~$ ./assign4.phpEnter the name of the file you wish to open /etc/crontabArray()bigjim3@bigjim3-desktop:~$ Thoughts, Suggestions, Hints?TIA

Link to comment
Share on other sites

  • 2 weeks later...

You are using fgets with a filename. fgets uses a file handle resource from fopen, not a filename. If you are using PHP greater then 4.3, then you can use file_get_contents to get the entire contents of a file in a string, and you can use the filename with that:http://www.php.net/manual/en/function.file-get-contents.phpThat would return the entire contents in a string. If you want to split that up into lines, then use the explode function and split it on \n. The result will be an array of the lines in the file.

Link to comment
Share on other sites

You are using fgets with a filename. fgets uses a file handle resource from fopen, not a filename. If you are using PHP greater then 4.3, then you can use file_get_contents to get the entire contents of a file in a string, and you can use the filename with that:http://www.php.net/manual/en/function.file-get-contents.phpThat would return the entire contents in a string. If you want to split that up into lines, then use the explode function and split it on \n. The result will be an array of the lines in the file.
Thanks for the info. Already turned in the assignment using the system grep function but will try this when I get the time.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...