So I know how to open a file in php is done using
fopen("file.txt", 'r') ;
but i want to get one line in the file and so some string manipulation on it.
such as " Serving this with <0101010> "
I want to find the line that starts with "Serving this" and take the whole line add it to $line
Then i will get remove the <> and add it to $number , and same for <0101010>
names of methods that can be used would 开发者_如何学Cbe just perfect
Okay, the simple method you probably want to use is:
foreach (file("file.txt") as $line) {
if (strpos($line, "Serving this with") === 0) {
print "found";
The file
function is easier than fopen/fread, as it returns a list of lines already. And the strpos
function simply searches the string and returns the position. It must be checked with === 0
here, because it could also return false
.
Instead of printing "found" you want to extract something, so you must again use strpos
to find your delimeters <
and >
and then extract the part with substr
:
$l = strpos($line, "<"); // well, actually needs more logic,
$r = strpos($line, ">"); // some if tests, if both are true
$wanthave = substr($line, $l, $r - $l + 1);
A simpler option I would use are regular expressions. And the regex itself looks simple enough in your case:
preg_match_all('/^Serving this with <(\d+)>/m',
file_get_contens("file.txt"),
$matches);
print_r($matches[1]);
you can also use fgets() read file line by line.
$line = fgets($file_handle);
精彩评论