Search code examples
phpstrpos

Get value from file - 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.


Solution

  • 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;
        }
    }