从文件中获取价值 - php

Let's say I have this in my text file:

Author:MJMZ
Author URL:http://abc.co
Version: 1.0

How can I get the string "MJMZ" if I look for the string "Author"?

I already tried the solution from another question (Php get value from text file) but with no success.

The problem may be because of the strpos function. In my case, the word "Author" got two. So the strpos function can't solve my problem.

Split each line at the : using explode, then check if the prefix matches what you're searching for:

$lines = file($filename, FILE_IGNORE_NEW_LINES);
foreach($lines as $line) {
    list($prefix, $data) = explode(':', $line);
    if (trim($prefix) == "Author") {
        echo $data;
        break;
    }
}

Try the following:

$file_contents = file_get_contents('myfilename.ext');
preg_match('/^Author\s*\:\s*([^
]+)/', $file_contents, $matches);
$code = isset($matches[1]) && !empty($matches[1]) ? $matches[1] : 'no-code-found';

echo $code;

Now the $matches variable should contains the MJMZ.

The above, will search for the first instance of the Author:CODE_HERE in your file, and will place the CODE_HERE in the $matches variable.

More specific, the regex. will search for a string that starts with the word Author followed with an optional space \s*, followed by a semicolon character \:, followed by an optional space \s*, followed by one or more characters that it is not a new line [^ ]+.

If your file will have dinamically added items, then you can sort it into array.

$content = file_get_contents("myfile.txt");
$line = explode("
", $content);
$item = new Array();
foreach($line as $l){
    $var = explode(":", $l);
    $value = "";

    for($i=1; $i<sizeof($var); $i++){
        $value .= $var[$i];
    }

    $item[$var[0]] = $value;
}
// Now you can access every single item with his name:
print $item["Author"];

The for loop inside the foreach loop is needed, so you can have multiple ":" in your list. The program will separate name from value at the first ":"

First take lines from file, convert to array then call them by their keys.

$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$pieces = explode(":", $line);
$array[$pieces[0]] = $pieces[1];
 }
} else {
// error opening the file.
} 
fclose($handle);
echo $array['Author'];