| Register | FAQ | Calendar | Search | Today's Posts | Mark Forums Read |
|
#11
| |||
| |||
| 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 > bbb qr> [...] > > > 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; } |
![]() |
| Thread Tools | |
| Display Modes | |
In an effort to better serve ads to our visitors, cookies are used on objectmix.com. For more information, check out our Privacy Policy.