how to get line from file, like grep

This is a discussion on how to get line from file, like grep within the PHP forums in Programming Languages category; mijn naam wrote: > "mijn naam" <whatever @ hotmail.invalid> schreef in bericht > news:6d5cb$48b48b34$53565551$17128 @ cache100.multik abel.net... >> Hi, >> >> I tried searching myself using google and on php.net, but too much >> irrelevant answers and not a single one helpful so please bare with me. >> >> Could someone please show me how to get one line from a file, much >> like unix "grep '^needle' haystack" ? >> >> I'm sure there are zero or one matches, and I don't need fancy regular >> expressions, just a string to be found at the beginning of a line. ...

Go Back   Application Development Forum > Programming Languages > PHP

Object Mix

Register FAQ Calendar Search Today's Posts Mark Forums Read
  #11  
Old 08-28-2008, 12:31 AM
Curtis
Guest
 
Default Re: how to get line from file, like grep

mijn naam wrote:
> "mijn naam" <whatever@hotmail.invalid> schreef in bericht
> news:6d5cb$48b48b34$53565551$17128@cache100.multik abel.net...
>> Hi,
>>
>> I tried searching myself using google and on php.net, but too much
>> irrelevant answers and not a single one helpful so please bare with me.
>>
>> Could someone please show me how to get one line from a file, much
>> like unix "grep '^needle' haystack" ?
>>
>> I'm sure there are zero or one matches, and I don't need fancy regular
>> expressions, just a string to be found at the beginning of a line.
>> That string won't be the entire line though.

>
>
> Thanks all. As expected there are many solutions. I got one from
> elsewhere as well.
>
> Part of the problem (which I did not mention) is that I needed only the
> rest of the line.
> So, for "xyz:abc" I'm only interested in "abc". The following function
> does this. What do you think of it?
>
> The file is:
> aaa:xyz
> xyz:abc
> bbbqr
> [...]
>
>
> function match($what,$where) {
> $x=file_get_contents($where);
> $a=explode("\n",$x);
> $b=preg_grep("/^{$what}:/",$a);
> if (count($b)!=1) return FALSE;
> $b=implode("",$b);
> $b=explode(":",$b);
> if (count($b)!=2) return FALSE;
> $b=$b{1};
> return $b;
> }


If you want to grab the file in an array of lines, use the file()
function. This method is a bit clearer:

function match($needle, $file) {
$ret = false;
$lines = file($file);

foreach ( $lines as $line ) {
list($key,$val) = explode(':',$line);
$ret = $key==$needle ? $val : false;
if ( $ret ) break;
}

return $ret;
}
Reply With Quote
Reply


Thread Tools
Display Modes


All times are GMT -5. The time now is 10:41 AM.


Powered by vBulletin® Version 3.7.2
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.2.0
vB Ad Management by =RedTyger=

In an effort to better serve ads to our visitors, cookies are used on objectmix.com. For more information, check out our Privacy Policy.